Unit testing. java.lang.NullPointerException - android-studio

everyone! I am writing unit tests for the mobile app. But I have an error that I don't know how to solve. The error has the following form:
java.lang.NullPointerException
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:841)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223)
at com.example.projectMP3.SplashScreenActivityTest.testLaunchOfNewActivity(SplashScreenActivityTest.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Program code "SplashScreenActivity.java":
public class SplashScreenActivity extends AppCompatActivity {
LinearLayout linearLayout;
/** Toolbar */
androidx.appcompat.widget.Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
toolbar = findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
linearLayout = findViewById(R.id.Splash_Activity);
linearLayout.setOnClickListener(v -> {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
finish();
});
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
Objects.requireNonNull(getSupportActionBar()).hide();
Thread thread = new Thread() {
public void run() {
try {
sleep(3000);
} catch (Exception e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(SplashScreenActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
}
};
thread.start();
}
}
Program code "SplashScreenActivityTest.java":
import android.widget.TextView;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
public class SplashScreenActivityTest {
#Test
public void testLaunchOfNewActivity() {
SplashScreenActivity activity = new SplashScreenActivity();
TextView nameApplication = activity.findViewById(R.id.textView3);
assertNotNull(nameApplication.getText());
}
}
Program code "activity_splash_screen.xml":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/Splash_Activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
android:orientation="vertical"
tools:context=".SplashScreenActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#drawable/tab_indicater"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="320dp"
android:layout_height="320dp"
android:layout_gravity="center_horizontal"
app:srcCompat="#drawable/splash_screen_logo"
android:layout_marginTop="100dp"
app:tint="#120a8f"
android:contentDescription="#string/startSplashScreen" />
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:gravity="center"
android:text="#string/appName"
android:textColor="#FFAB00"
android:textSize="50sp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginTop="2dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/all_rights_are_reserved"
android:textColor="#color/white"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
This is my first time writing unit tests. I hope for your help! Thank you in advance.

The issue related to your Activity class. You just tried to test activity like a simple class. But in the android, Activity it's a system component managed by the system, and you can't just create an Activity using constructor.
On the official site it has a documentation how to test an activity:
https://developer.android.com/guide/components/activities/testing

It seems you are calling the activity and accessing the UI component in that activity. I don't know if you can do that in unit test without launching the app which makes it Instrumented test(which should be tested with AndroidJunit4)

Related

Kotlin "D/skia: --- Failed to create image decoder with message 'unimplemented'" Error preventing functionality of button at login/registration screen

Hello I am currently facing an issue with my Kotlin code in Android SDK. For the purposes of a small personal project I am trying to get a simple change password functionality working with a nodeJS file and mongoDB. However I've run into the issue while writting up some code to this end. It seems that my change_password function doesn't want to launch the sequence to input the new password due to the following error "D/skia: --- Failed to create image decoder with message 'unimplemented'" which is only visible in the debug mode. I am not even certain where to start debugging this issue, so I'm hoping someone here might be able to help. Bellow I have provided my MainActivity file where the change_password function is present. Additionally I have provided the xml layout files involved in these operations.
MainActivity File
import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.afollestad.materialdialogs.MaterialDialog
import com.example.accentus_login.R.id.*
import com.example.accentus_login.Retrofit.INodeJS
import com.example.accentus_login.Retrofit.RetrofitClient
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.rengwuxian.materialedittext.MaterialEditText
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.home_page.*
import org.jetbrains.anko.toast
class MainActivity : AppCompatActivity() {
lateinit var myAPI: INodeJS
var compositeDisposable = CompositeDisposable()
var m_bluetoothAdapter: BluetoothAdapter? = null
lateinit var m_pairedDevices: Set<BluetoothDevice>
val REQUEST_ENABLE_BLUETOOTH=1
internal lateinit var change_pass_confirm_button: Button
companion object{
val EXTRA_ADDRESS: String = "Device_address"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Init API
val retrofit = RetrofitClient.instance
myAPI = retrofit.create(INodeJS::class.java)
//m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
//if (m_bluetoothAdapter==null){
// toast("this device doesn't support bluetooth")
// return
//}
//if(!m_bluetoothAdapter!!.isEnabled) {
// val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
// if (ActivityCompat.checkSelfPermission(
// this,
// Manifest.permission.BLUETOOTH_CONNECT
// ) != PackageManager.PERMISSION_GRANTED
// ) {
// ActivityCompat.requestPermissions(
// this#MainActivity,
// arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN),REQUEST_ENABLE_BLUETOOTH)
// }
// startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
//}
//select_device_refresh.setOnClickListener{ pairedDeviceList() }
//change_pass_confirm_button = findViewById(R.id.change_pass_confirm_button);
login_button.setOnClickListener{
login(edt_email.text.toString(),edt_password.text.toString())
}
register_button.setOnClickListener{
register(edt_email.text.toString(),edt_password.text.toString())
}
change_pass_button.setOnClickListener{
change_password(edt_email.text.toString())
}
}
private fun login(email: String, password: String) {
compositeDisposable.add(myAPI.loginUser(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe{ message ->
if (message.contains("encrypted_password"))
Toast.makeText(this#MainActivity,"Login Successful",Toast.LENGTH_SHORT).show()
else
Toast.makeText(this#MainActivity,message,Toast.LENGTH_SHORT).show()
setContentView(R.layout.home_page);
})
}
private fun change_password(email: String) {
val change_pass_view = LayoutInflater.from(this#MainActivity)
.inflate(R.layout.change_pass, null)
MaterialStyledDialog.Builder(this#MainActivity)
.setTitle("Change Password")
.setDescription("Enter New Password")
.setCustomView(change_pass_view)
.setNegativeText("Cancel")
.onNegative { materialDialog: MaterialDialog -> materialDialog.dismiss() }
.setPositiveText("Confirm")
.onPositive { materialDialog: MaterialDialog ->
val password = change_pass_view.findViewById(R.id.new_pass) as MaterialEditText
//val con_password = change_pass_view.findViewById(R.id.con_new_pass) as MaterialEditText
if (password != password)
Toast.makeText(this#MainActivity, "Password Doesn't Match", Toast.LENGTH_SHORT)
.show()
else
compositeDisposable.add(myAPI.ChangePass(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { message ->
Toast.makeText(this#MainActivity, message, Toast.LENGTH_SHORT).show()
})
}
}
private fun register(email: String, password: String) {
val enter_name_view = LayoutInflater.from(this#MainActivity)
.inflate(R.layout.enter_name_layout,null)
MaterialStyledDialog.Builder(this#MainActivity)
.setTitle("Register")
.setDescription("Last Step: Enter your Name")
.setCustomView(enter_name_view)
.setIcon(R.drawable.ic_user)
.setNegativeText("Cancel")
.onNegative{ materialDialog: MaterialDialog-> materialDialog.dismiss() }
.setPositiveText("Register")
.onPositive { materialDialog: MaterialDialog ->
val edt_name = enter_name_view.findViewById<View>(edt_name) as MaterialEditText
compositeDisposable.add(myAPI.registerUser(email,edt_name.text.toString(), password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe{ message ->
Toast.makeText(this#MainActivity,message,Toast.LENGTH_SHORT).show()
})
}.show()
}
private fun pairedDeviceList(){
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this#MainActivity,
arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN),REQUEST_ENABLE_BLUETOOTH)
}
m_pairedDevices = m_bluetoothAdapter!!.bondedDevices
val list : ArrayList<BluetoothDevice> = ArrayList()
if(m_pairedDevices.isNotEmpty()) {
for(device : BluetoothDevice in m_pairedDevices) {
list.add(device)
Log.i("device", ""+device) // device logged as string
}
} else {
toast("no paired bluetooth devices found")
}
val adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,list)
select_device_list.adapter=adapter
select_device_list.onItemClickListener= AdapterView.OnItemClickListener{ _, _, position, _ ->
val device: BluetoothDevice= list[position]
val address: String = device.address
val intent = Intent(this, ControlActivity::class.java)
intent.putExtra(EXTRA_ADDRESS,address)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode==REQUEST_ENABLE_BLUETOOTH){
if(resultCode== Activity.RESULT_OK) {
if (m_bluetoothAdapter!!.isEnabled) {
toast("Bluetooth has been enabled")
} else {
toast("Bluetooth has been disabled")
}
} else if (resultCode == Activity.RESULT_CANCELED)
toast("Bluetooth enabling has been canceled")
}
}
override fun onStop() {
compositeDisposable.clear()
super.onStop()
}
override fun onDestroy() {
compositeDisposable.clear()
super.onDestroy()
}
XML Login Page
<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"
android:background="#drawable/gradient_bg"
tools:context=".MainActivity">
<LinearLayout
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<TextView
android:text="#string/accentus"
android:textSize="30sp"
android:textColor="#android:color/white"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edt_email"
android:hint="#string/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
app:met_iconLeft="#drawable/ic_user"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edt_password"
android:hint="#string/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_iconLeft="#drawable/ic_lock"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/register_button"
android:text="#string/register_account"
android:layout_marginEnd="8dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
<com.google.android.material.button.MaterialButton
android:id="#+id/login_button"
android:text="#string/login"
android:layout_marginStart="8dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/change_pass_button"
android:text="#string/forgot_password"
android:layout_marginStart="125dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML Change Password Page
<?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"
android:background="#drawable/gradient_bg"
tools:context=".MainActivity">
<LinearLayout
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<TextView
android:text="#string/change_password"
android:textSize="30sp"
android:textColor="#android:color/white"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/login_email"
android:hint="#string/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/new_pass"
android:hint="#string/new_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/con_new_pass"
android:hint="#string/confirm_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_iconLeft="#drawable/ic_lock"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Please let me know if you think there is any other information necessary to understand why this is going on.

Why does Unexpected implicit cast to `EditText`: layout tag was `TextView`

I have a problem, I'm trying to finish the lesson Android fundamentals 02.3: Implicit intents, but there are some errors
the first one is Unexpected implicit cast to EditText: layout tag was TextView
the second one is Consider adding a declaration to your manifest when calling this \ method; see https://g.co/dev/packagevisibility for details
when running the application, it automatically stops immediately, I have tried it on the emulator and on real devices
source codelab : https://developer.android.com/codelabs/android-training-activity-with-implicit-intent?index=..%2F..%2Fandroid-training#0
Code MainActivity.java
package com.example.implicitintents;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText mWebsiteEditText;
private EditText mLocationEditText;
private EditText mShareTextEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebsiteEditText = findViewById(R.id.website_edittext);
mLocationEditText = findViewById(R.id.location_edittext);
mShareTextEditText = findViewById(R.id.share_edittext);
}
public void openWebsite(View view) {
String url = mWebsiteEditText.getText().toString();
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
public void openLocation(View view) {
String loc = mLocationEditText.getText().toString();
Uri addressUri = Uri.parse("geo:0,0?q=" + loc);
Intent intent = new Intent(Intent.ACTION_VIEW, addressUri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
public void shareText(View view) {
String txt = mShareTextEditText.getText().toString();
String mimeType = "text/plain";
ShareCompat.IntentBuilder
.from(this)
.setType(mimeType)
.setChooserTitle("Share this text with: ")
.setText(txt)
.startChooser();
}
}
Code Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="16dp"
tools:context="MainActivity">
<TextView
android:id="#+id/website_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_uri" />
<Button
android:id="#+id/open_website_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:onClick="openWebsite"
android:text="#string/button_uri" />
<TextView
android:id="#+id/location_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_loc" />
<Button
android:id="#+id/open_location_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:onClick="openLocation"
android:text="#string/button_loc" />
<TextView
android:id="#+id/share_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_share" />
<Button
android:id="#+id/share_text_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:onClick="shareText"
android:text="#string/button_share" />
</LinearLayout>
In your xml file you declare three elements as Textview
<TextView
android:id="#+id/website_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_uri" />
<TextView
android:id="#+id/location_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_loc" />
<TextView
android:id="#+id/share_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/edittext_share" />
And then in your activity you declare your variables as EditText
private EditText mWebsiteEditText;
private EditText mLocationEditText;
private EditText mShareTextEditText;
And that's why your seeing those errors of casting.
Change in your xml file to EditText if you want to input some data or leave it like TextView if you want display some text but change the type of your variables in the activity. Make sure both are the same type

Android Studio: Click TextView to open an Specific Image on other Activity (Click Index Title to Open page on other Activity)

I m Developing Book Reading Project on Android studio, it has index activity with all titles and page numbers, when some one click on any title of index so on the an other activity the specific image should be open. all images are in Drawable folder.
here is XML Coding of First Activity coding Activity_main3.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:stretchColumns="0,1,2"
android:gravity="center"
android:shrinkColumns="1">
<TableRow
android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
>
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="0"
android:layout_margin="1dp"
android:autoSizeTextType="uniform"
android:background="#FFFFFF"
android:gravity="center"
android:text="ناشر پاران...5"
android:textAppearance="?android:attr/textAppearanceLarge" />
/>
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="2"
android:layout_margin="1dp"
android:autoSizeTextType="uniform"
android:background="#FFFFFF"
android:gravity="center"
android:text="پنهنجي پاران...6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
The Second Activty coding is like this Activity_main.xml
<android.support.constraint.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="org.sindhila.www.sindhi_school_linguistics.MainActivity"
tools:layout_editor_absoluteY="81dp">
<Button
android:id="#+id/SwitchImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:text="Next"
app:layout_constraintBaseline_toBaselineOf="#+id/SwitchImage2"
app:layout_constraintEnd_toStartOf="#+id/SwitchImage2"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#mipmap/pic3" />
<Button
android:id="#+id/SwitchImage2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:text="Previous"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/SwitchImage" />
and Here is Coding Of mainactivity.java
it has two buttons for next and previous page and an image view to open images from drawable folder
package org.sindhila.www.sindhi_school_linguistics;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import java.util.Locale;
import uk.co.senab.photoview.PhotoViewAttacher;
public class MainActivity extends AppCompatActivity {
private static ImageView imageView;
private static Button SwitchImage;
private static Button SwitchImage2;
//
PhotoViewAttacher photoViewAttacher;
////
private int current_image_index;
int images[] = {R.mipmap.pic1, R.mipmap.pic2, R.mipmap.pic3,
R.mipmap.pic4,
R.mipmap.pic5,
R.mipmap.pic6,
R.mipmap.pic7,
R.mipmap.pic8,
R.mipmap.pic9,
R.mipmap.pic10,
R.mipmap.pic11,
R.mipmap.pic12,
R.mipmap.pic13,
R.mipmap.pic14,
R.mipmap.pic15,
R.mipmap.pic16,
R.mipmap.pic17,
R.mipmap.pic18,
R.mipmap.pic19,
R.mipmap.pic20,
R.mipmap.pic21,
R.mipmap.pic22,
R.mipmap.pic23,
R.mipmap.pic24,
R.mipmap.pic25,
R.mipmap.pic26,
R.mipmap.pic27,
R.mipmap.pic28,
R.mipmap.pic29,
R.mipmap.pic30,
R.mipmap.pic31,
R.mipmap.pic32,
R.mipmap.pic33,
R.mipmap.pic34,
R.mipmap.pic35,
R.mipmap.pic36,
R.mipmap.pic37,
R.mipmap.pic38,
R.mipmap.pic39,
R.mipmap.pic40,
R.mipmap.pic41,
R.mipmap.pic42,
R.mipmap.pic43,
R.mipmap.pic44,
R.mipmap.pic45,
R.mipmap.pic46,
R.mipmap.pic47,
R.mipmap.pic48,
R.mipmap.pic49,
R.mipmap.pic50,
R.mipmap.pic51,
R.mipmap.pic52,
R.mipmap.pic53,
R.mipmap.pic54,
R.mipmap.pic55,
R.mipmap.pic56,
R.mipmap.pic57,
R.mipmap.pic58,
R.mipmap.pic59,
R.mipmap.pic60,
R.mipmap.pic61,
R.mipmap.pic62,
R.mipmap.pic63,
R.mipmap.pic64,
R.mipmap.pic65,
R.mipmap.pic66,
R.mipmap.pic67,
R.mipmap.pic68,
R.mipmap.pic69,
R.mipmap.pic70,
R.mipmap.pic71,
R.mipmap.pic72,
R.mipmap.pic73,
R.mipmap.pic74,
R.mipmap.pic75,
R.mipmap.pic76,
R.mipmap.pic77,
R.mipmap.pic78,
R.mipmap.pic79,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
buttonClick2();
//////
imageView = (ImageView)findViewById(R.id.imageView);
Drawable drawable = getResources().getDrawable(R.mipmap.pic1);
imageView.setImageDrawable(drawable);
photoViewAttacher = new PhotoViewAttacher(imageView);
photoViewAttacher.update();
//////
}
public void buttonClick() {
imageView = (ImageView) findViewById(R.id.imageView);
SwitchImage = (Button) findViewById(R.id.SwitchImage);
SwitchImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
}
}
);
}
public void buttonClick2() {
imageView = (ImageView) findViewById(R.id.imageView);
SwitchImage2 = (Button) findViewById(R.id.SwitchImage2);
SwitchImage2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (current_image_index!=0) {
current_image_index--;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
}
}
}
);
}
}
Every thing is working Fine, i need to have hyperlink on Textview (on Activity_main3.xml and Main3Activity.java) to open specific image on Activity_main.xml/MainActivity.java
i have used following Coding but it produce error how to solve it please help. i want to click a textview on one activity and open specific image on other activity in imageview
in xml file of first activity in textview i added
android:onClick="onClick"
android:clickable="true"
.... added coding to first index activity named Main3activity.java where textviews are placed when I click textview it should open other activity and an image in it
public void onClick(View v) {
Intent intent = new Intent(Main3Activity.this,
MainActivity.class);
intent.putExtra("pic", pic4.png);
startActivity(intent);
} ...
and this coding to mainactivity.java where image should be opened in image view
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
buttonClick2();
setContentView(R.mipmap.pic1);
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageResource(getIntent().getIntExtra("img", 0));

Android Floating Action Button Behaviour with Adview

I'm sorry if this has been already answered but it's been a while and I'm still searching. Since the FAB has a behaviour class you can assign to it which will work with scrolling inside a coordinator layout, I was wondering if it was possible to include behaviour to make the FAB automatically get placed above an adview when it is visible similar to how it reacts to a snack bar. Thank you in advance.
Work Around!
I figured out a work around as I was just playing around some time back, even forgot about the question. Instead of putting my adview inside a container with the rest of my views I simply had to wrap the coordinator view in a Relative layout and set the coordinator layout above the adview ID. I'm sure this might not be the best way to do it.
So what I ended up having is this: NB My adview is set to visibility gone by default and I only set the visibility when the adrequest is complete
<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">
<android.support.design.widget.CoordinatorLayout
android:layout_above="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:visibility="gone"
app:layout_behavior="utils.FabBehavior_Main"
app:rippleColor="#color/fab_ripple"
app:srcCompat="#drawable/ic_fab" />
</android.support.design.widget.CoordinatorLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone"
app:adSize="SMART_BANNER"
app:adUnitId="#string/banner_ad_unit_id"
/>
</RelativeLayout>
The utils.FabBehavior_Main is the relative package class that contains the behaviour properties for the view, utils being the package. So in your own application you could have the name space com.myapp.utils.ScrollAwareFab which would have be like this:
public class ScrollAwareFab extends FloatingActionButton.Behavior {
public ScrollAwareFab(Context context, AttributeSet attrs) {
super();
}
#Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
#Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
/**
* Called when a FloatingActionButton has been hidden
*
* #param fab the FloatingActionButton that was hidden.
*/
#Override
public void onHidden(FloatingActionButton fab) {
super.onShown(fab);
fab.setVisibility(View.INVISIBLE);
}
});
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
}

Hiding View after async call to the server completed

I'm trying to have a preloader to show while my request to the server is waiting for response
but when I try to hide the preloader with setVisibility(View.GONE); it doesn't hide (even though the other content does get visible)
when I run the function that suppose to remove the preloader and show the other content directly (not in the callback of the async request - it works)
my layout looks like this (I removed all the irrelevant stuff like the android:text properties etc.):
[notice that the loader I'm using is a custom view I made (I don't know if it has anything to do with the problem]
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/logo" />
<views.Loader
android:id="#+id/preloader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:id="#+id/buttonsArea"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_dance"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/another_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
notice that the loader I'm using is a custom view (I don't know if it has anything to do with the problem)
My Java code is:
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_page);
init();
setLoading(true);
loadData();
}
private void init(){
preloader = (Loader) findViewById(R.id.preloader);
buttonsArea= (LinearLayout) findViewById(R.id.buttonsArea);
}
private void loadData(){
app.getManager().app_init(new OnAppInfoResponse(){
#Override
public void onResponse(boolean success) {
//this method runs on UI Thread through Handler
setLoading(false);
}
});
}
private void setLoading(boolean loading) {
this.loading = loading;
if(loading){
buttonsArea.setVisibility(View.GONE);
preloader.setVisibility(View.VISIBLE);
} else {
buttonsArea.setVisibility(View.VISIBLE);
preloader.setVisibility(View.GONE);
}
}
Edit:
even weirder:
when I remove the buttonsArea.setVisibility(View.VISIBLE); line, the preloader does get hidden!
Thank you very much!!

Resources