Start IntentService from other App - android-intentservice

I´m trying to start a IntentService from other App, now I have an Activity with an AsyncTask where I download a file. This works fine but I want download the file in a IntentService and don´t have to show the activity, just a Notification. Is this possible? I have read that IntentService starts when a Activity calls it through startService(Intent), but when I try nothing happens :(
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bajar);
intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
id = new Descarga(todo);
EditText textNombre = (EditText) findViewById(R.id.TextNombre);
textNombre.setText(id.nombre);
/*
This works
d = new Download();
d.execute();
/*
startService(intent); //This don´t work
}
}
}
}
This is the Activity xml file:
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="es.esy.palmaseca.descargayt.Bajar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/nombre"
android:id="#+id/txtNombre"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextNombre"
android:layout_below="#+id/txtNombre"
android:layout_centerHorizontal="true"
android:editable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/txtActual"
android:layout_marginTop="44dp"
android:layout_below="#+id/TextNombre"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/txtFinal"
android:layout_below="#+id/txtActual"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/barra"
android:layout_below="#+id/txtFinal"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp" />
My Class IntentService:
public class Descargar extends IntentService {
NotificationManager nm;
Notification notification;
static String ns = Context.NOTIFICATION_SERVICE;
int icono = R.drawable.icono;
public Descargar() {
super("Descargar");
Log.d("Serivicio", "Star");
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
Descarga d = new Descarga(todo);
bajar(d);
}
}
}
}
The function bajar is the same as Download AsynTask.
And finally the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.esy.palmaseca.descarga" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/icono"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:enabled="true"
android:name=".Descargar"
android:exported="true" >
</service>
<activity
android:name=".Bajar"
android:label="#string/bajar" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
I have tried to start the IntentService but I can´t find out where is the mistake, and throws 0 errors
Sorry my english 🙏

An easy solution is to create a BroadcastReceiver, register it in your manifest for some intent action and then have it start the intentservice.
public class Descargar extends IntentService {
NotificationManager nm;
Notification notification;
static String ns = Context.NOTIFICATION_SERVICE;
int icono = R.drawable.icono;
public static class DescargarReceiver implements BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), Descargar.class.getName());
context.startService(intent.setComponent(comp));
}
}
public Descargar() {
super("Descargar");
Log.d("Serivicio", "Star");
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
Descarga d = new Descarga(todo);
bajar(d);
}
}
}
}
and in the manifest:
<receiver
android:name=".Descargar$DescargarReceiver"
android:exported="true>
<intent-filter>
<action
android:name="com.mycompany.action.START_DESCARGAR_SERVICE" />
</intent-filter>
</receiver>
<service
android:enabled="true"
android:name=".Descargar"
android:exported="true" >
</service>
and then you can just broadcast the intent from any app:
Intent intent = new Intent("com.mycompany.action.START_DESCARGAR_SERVICE");
intent.putExtra(.....)
sendBroadcast(intent);

Related

How to retrieve data from firebase into a recycler view using Kotlin (including images)?

I'm retrieving data from firebase into a recycler view using Kotlin. I'm able to load the text easily but unable to load the images. I have used Picasso library for the same. There is no error in the code, can anyone suggest something?
Following is my code:
1) This is the main activity class
class MainActivity : AppCompatActivity()
{
lateinit var recyclerView: RecyclerView
lateinit var ref:DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView=findViewById(R.id.rvFirebase)
ref= FirebaseDatabase.getInstance().reference.child("Restaurants")
recyclerView.layoutManager=LinearLayoutManager(this)
val option=FirebaseRecyclerOptions.Builder<ResModel>().setQuery(ref,ResModel::class.java).build()
val firebaseRecyclerAdapter= object :FirebaseRecyclerAdapter<ResModel,RViewHolder>(option){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RViewHolder {
val itemView= LayoutInflater.from(this#MainActivity).inflate(R.layout.single_row,parent,false)
return RViewHolder(itemView)
}
override fun onBindViewHolder(holder: RViewHolder, position: Int, model: ResModel) {
val refId = getRef(position).key.toString()
ref.child(refId).addValueEventListener(object:ValueEventListener{
override fun onCancelled(error: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
holder.rCost.text = model.resCost
holder.rName.text = model.resName
Picasso.get().load(model.resImage).into(holder.rImage)
holder.rRating.text=model.resRating
}
})
}
}
recyclerView.adapter=firebaseRecyclerAdapter
firebaseRecyclerAdapter.startListening()
}
class RViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
var rImage:ImageView=itemView.findViewById(R.id.imgRestaurant)
var rName:TextView=itemView.findViewById(R.id.txtRestaurantName)
var rCost:TextView=itemView.findViewById(R.id.txtCost)
var rRating:TextView=itemView.findViewById(R.id.txtResRating)
}
}
2) This is the model class
class ResModel
{
var resCost: String =" "
var resImage: String=" "
var resName: String=" "
var resRating: String=" "
constructor():this("","","",""){
}
constructor(resCost:String,resImage: String,resName:String,resRating:String){
this.resCost=resCost
this.resImage=resImage
this.resName=resName
this.resRating=resRating
}
}
3)This is the main activity 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="wrap_content"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:id="#+id/rvFirebase"/>
</RelativeLayout>
4) This is the card view xml file which is being used in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
app:cardCornerRadius="4dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/carViewXml">
<LinearLayout
android:id="#+id/llContent"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:background="#ffffff"
android:weightSum="6">
<ImageView
android:layout_marginTop="6dp"
android:layout_weight="1.7"
android:id="#+id/imgRestaurant"
android:layout_width="0dp"
android:layout_height="90dp"
android:src="#drawable/ic_food"
android:padding="5dp"
android:layout_marginStart="10dp"
android:scaleType="centerCrop"
android:fadingEdge="vertical"
android:background="#drawable/rounded_image"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:layout_weight="3.3"
android:layout_marginStart="5dp">
<TextView
android:id="#+id/txtRestaurantName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:text="name_of_the_restaurant"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/txtCost"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#id/txtRestaurantName"
android:layout_alignParentBottom="true"
android:layout_marginTop="20dp"
android:layout_marginBottom="0dp"
android:padding="8dp"
android:text="Rs. 299"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="9dp"
android:layout_weight="1"
android:layout_marginStart="3dp">
<ImageView
android:id="#+id/imgFavResIcon"
android:layout_width="match_parent"
android:layout_height="23dp"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp"
android:src="#drawable/ic_favorite_res" />
<TextView
android:id="#+id/txtResRating"
android:layout_width="match_parent"
android:layout_height="53dp"
android:layout_below="#id/imgFavResIcon"
android:layout_marginTop="22dp"
android:padding="4dp"
android:text="4.5"
android:textAlignment="center"
android:textColor="#FB8C00"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
4) This is the image of how I stored data on firebase database and storage
Firebase Databse
Firebase storage
Not sure how Picasso can handle Firebase ui storage but with glide you do something like this:
implementation 'com.firebaseui:firebase-ui-storage:6.3.0' add firebase UI Storage
Then:
val storageReference: StorageReference = model.resImage //not sure about the reference here - eg FirebaseStorage.getInstance().getReference().child("yourImageReferencePath")
Glide.with(this /* context */)
.using(FirebaseImageLoader())
.load(storageReference)
.into(holder.rImage)
Also please take a look at other resources

Image capture and upload inside a fragment in kotlin

THIS IS MY XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MakeComplaint.Category_Description"
android:background="#drawable/fragmentgradient_bg">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/heading_constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteX="17dp">
<ImageView
android:id="#+id/backToHistory"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingHorizontal="20dp"
android:layout_weight="2"
android:src="#drawable/ic_backarrow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toLeftOf="#+id/location_title"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/location_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingHorizontal="20dp"
android:fontFamily="#font/pathway_gothic_one"
android:gravity="center"
android:textSize="40sp"
android:text="Further Details"
app:layout_constraintHorizontal_bias="0.35"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="#+id/backToHistory"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.cardview.widget.CardView
android:id="#+id/details_card"
android:layout_width="0dp"
android:layout_height="0dp"
android:elevation="#dimen/card_spacing"
app:cardUseCompatPadding="true"
app:layout_constraintTop_toBottomOf="#+id/heading_constraint"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:cardCornerRadius="#dimen/card_spacing"
>
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/inner_constraint"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/card_spacing">
<TextView
android:id="#+id/guide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/pathway_gothic_one"
android:gravity="left"
android:text="Please enter any further details you would like to add:"
android:textSize="20sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/description_text_input"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:boxStrokeColor="#color/teal"
app:boxStrokeWidth="#dimen/card_spacing"
app:counterEnabled="true"
app:counterMaxLength="500"
android:hint="Additional Notes"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/guide"
app:prefixTextColor="#color/colorPrimaryDark"
android:outlineAmbientShadowColor="#color/teal"
android:outlineSpotShadowColor="#color/teal"
android:scrollbarAlwaysDrawHorizontalTrack="true"
app:layout_constraintBaseline_creator="#android:integer/config_longAnimTime"
>
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapSentences|textMultiLine"
android:maxLength="500"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--ImageView where image will be set-->
<ImageView
android:id="#+id/display_image"
android:scaleType="centerCrop"
android:layout_width="250dp"
android:layout_height="250dp"
android:adjustViewBounds="true"
app:layout_constraintTop_toBottomOf="#+id/description_text_input"
app:layout_constraintBottom_toTopOf="#+id/FAB_buttons"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/FAB_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/description_text_input"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginVertical="5dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="#color/teal"
android:layout_marginHorizontal="#dimen/card_spacing"
android:src="#android:drawable/ic_menu_camera"
app:layout_constraintRight_toLeftOf="#+id/camera"
app:layout_constraintTop_toBottomOf="#+id/name_text_input"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="#color/teal"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/name_text_input"
android:src="#android:drawable/ic_menu_gallery"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make Complaint"
app:layout_constraintTop_toBottomOf="#+id/FAB_buttons"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:backgroundTint="#color/teal"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>```
**THIS IS MY KOTLIN FILE**
package com.example.atry.MakeComplaint
class Category_Description : Fragment() {
private val ALL_PERMISSIONS_RESULT = 107
private val IMAGE_RESULT = 200
private val REQUEST_IMAGE_CAPTURE = 12345
var mBitmap: Bitmap? = null
val permission = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(com.example.atry.R.layout.fragment_category__description, container, false)
val camera_FAB: View = v.findViewById(com.example.atry.R.id.camera)
val upload_FAB: View = v.findViewById(com.example.atry.R.id.upload)
val imageView = v.findViewById<ImageView>(com.example.atry.R.id.display_image)
upload_FAB.setOnClickListener {
pickImageFromGallery()
}
camera_FAB.setOnClickListener{
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val frag = this
/** Pass your fragment reference **/
frag.startActivityForResult(
intent,
REQUEST_IMAGE_CAPTURE
) // REQUEST_IMAGE_CAPTURE = 12345
}
fun hasPermissionInManifest(context: Context, permissionName: String): Boolean {
val packageName = context.packageName
try {
val packageInfo = context.packageManager
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)
val declaredPermisisons = packageInfo.requestedPermissions
if (declaredPermisisons != null && declaredPermisisons.size > 0) {
for (p in declaredPermisisons) {
if (p == permissionName) {
return true
}
}
}
} catch (e: PackageManager.NameNotFoundException) {
}
return false
}
v.backToHistory.setOnClickListener {
backFragment()
}
// Inflate the layout for this fragment
return v
}
private fun pickImageFromGallery() {
//Intent to pick image
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
companion object {
//image pick code
private val IMAGE_PICK_CODE = 1000;
//Permission code
private val PERMISSION_CODE = 1001;
}
private fun backFragment() {
val manager = (context as AppCompatActivity).supportFragmentManager
manager.popBackStackImmediate()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data !=null) {
if (requestCode == REQUEST_IMAGE_CAPTURE || requestCode== IMAGE_PICK_CODE) {
// Do something with imagePath
val extras = data.getExtras()
val photo = extras.get("data") as Bitmap
val imageView = view!!.findViewById<ImageView>(com.example.atry.R.id.display_image)
imageView.setImageBitmap(photo)
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
var selectedImage = activity.let { getImageUri( it!!,photo) }
val realPath = selectedImage.let { getRealPathFromURI(it) }
selectedImage = Uri.parse(realPath)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path =
MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(contentUri: Uri): String {
var cursor: Cursor? = null
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = getActivity()?.getContentResolver()?.query(contentUri, proj, null, null, null)
val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor!!.moveToFirst()
return cursor!!.getString(column_index)
} finally {
if (cursor != null) {
cursor!!.close()
}
}
}
}```
For capturing the image everything works fine until the screen appears where I click on the tick to approve that the picture is okay...but then I am unable to view anything on the ImageView.
For the upload button when I am on the screen that allows me to select the picture ...when i click on it the app crashes and gives me the following error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
I have searched the internet for days and couldn't find a proper solution to this. I would appreciate it if anyone could find me a solution to this.
URI of the selected image is not returned in Intent extras, but in the data of intent. You can get the selected image's URI as follows.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data !=null) {
if (requestCode == REQUEST_IMAGE_CAPTURE || requestCode== IMAGE_PICK_CODE) {
// Get image URI From intent
var imageUri = data.data
// do something with the image URI
your_image_view.setImageURI(imageUri)
}
}
super.onActivityResult(requestCode, resultCode, data)
}

Xamarin Android (PCL) Layout not correctly render in dependency service

I am trying to display a dialog on Android using Dependency Service. However, I could not get the design I create in android layout designer to display, the result comes out is different.
This is the screenshot of my previewer:
Expected design
This is the screenshot of my result:
Unexpected result
My axml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialogWrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:background="#drawable/backgroundstyle"
android:layout_marginRight="16dp"
android:stateListAnimator="#null">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="16dp"
android:textAlignment="center"
android:textColor="#000"
android:textSize="19sp"
android:text="TitleText"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:paddingBottom="16dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="4dp"
android:textAlignment="center"
android:text="subtitle test"
android:textColor="#000"
android:textSize="15sp" />
<RelativeLayout
android:id="#+id/RL_editTextWrapper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/subtitle"
android:padding="15dp"
>
<EditText
android:id="#+id/inputText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/roundedentry"
android:paddingBottom="8dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="8dp"
android:textAlignment="center"
android:textColor="#000"
android:text="inputText test"
android:textSize="15sp" />
</RelativeLayout>
<View
android:id="#+id/line"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/RL_editTextWrapper"
android:background="#cdced2" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/line"
android:orientation="horizontal">
<TextView
android:id="#+id/dialogButtonNO"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:stateListAnimator="#null"
android:textAlignment="center"
android:textColor="#007aff"
android:text="Cancel"
android:textSize="19sp" />
<View
android:id="#+id/separator"
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#cdced2" />
<TextView
android:id="#+id/dialogButtonOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:stateListAnimator="#null"
android:textAlignment="center"
android:textColor="#007aff"
android:textSize="19sp"
android:text="Ok"
android:textStyle="bold" />
</LinearLayout>
The #drawable/backgroundstyle code:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#android:color/white"/>
<corners
android:radius="16dp" />
This is the code for exporting dependency service in android:
namespace FFF.Droid.Native {
public class IOSDialogStyleDroid : IIOSDialogStyle {
public void ShowPopup(EntryPopup entryPopup) {
var context = CrossCurrentActivity.Current.Activity as FormsAppCompatActivity;
CustomDialog customDialog = new CustomDialog(context) {
entryPopup = entryPopup
};
customDialog.Show();
}
}
public class CustomDialog : Dialog {
public Context context { get; set; }
public EntryPopup entryPopup { get; set; }
public CustomDialog(Context context) : base(context) {
this.context = context;
}
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
RequestWindowFeature((int)WindowFeatures.NoTitle);
SetContentView(Resource.Layout.iOSStyleDialog);
EditText editText = FindViewById(Resource.Id.inputText) as EditText;
(FindViewById(Resource.Id.title) as TextView).Text = entryPopup.Title;
(FindViewById(Resource.Id.subtitle) as TextView).Text = entryPopup.Message;
var btnOk = FindViewById(Resource.Id.dialogButtonOK) as TextView;
btnOk.Text = entryPopup.okButton;
btnOk.Click += (object sender, EventArgs e) => {
entryPopup.OnPopupClosed(new EntryPopupClosedArgs {
Button = entryPopup.okButton,
Text = editText.Text
});
Dismiss();
};
var btnNo = FindViewById(Resource.Id.dialogButtonNO) as TextView;
btnNo.Text = entryPopup.cancelButton;
btnNo.Click += (object sender, EventArgs e) => {
entryPopup.OnPopupClosed(new EntryPopupClosedArgs {
Button = entryPopup.cancelButton,
Text = editText.Text
});
Dismiss();
};
}
}
I found out that textalignment seems broken, I use gravity instead.

How to make custom buttons in corona, Lua

I'm trying to make a mobile application with a screen that looks like this:
I'm making this using Corona, it's written in the Lua language
It's a scrollable list of buttons, I somewhat understand the scroll aspect. What I'm having problems now is making a button that can have more than one line of text and also an image. I've literally been searching for hour but haven't found anything (I'm probably bad at finding things). I think I'd have to create a custom button but I have no idea how to do this. I would appreciate some help with this be it a link or just some lines of text explaining it, thank you so much!
use custom view
custom_button_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iconImgV"
android:layout_alignParentRight="true"
android:layout_width="100dp"
android:layout_alignParentTop="true"
android:background="#ff0000"
android:layout_height="100dp" />
<TextView
android:id="#+id/titleTv"
android:textSize="18sp"
android:text="Title"
android:layout_toLeftOf="#+id/iconImgV"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/descriptionTv"
android:layout_width="wrap_content"
android:text="description"
android:textSize="14sp"
android:layout_below="#+id/titleTv"
android:layout_toLeftOf="#+id/iconImgV"
android:layout_height="wrap_content" />
</RelativeLayout>
and CustomButtonView.java
public class CustomButtonView extends RelativeLayout {
Context context;
//view
ImageView iconImgV;
TextView titleTv, descriptionTv;
//value
int drawableIcon;
String title,description;
public CustomButtonView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
public CustomButtonView(Context context) {
super(context);
init();
}
public CustomButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customButtonViewAttrs);
drawableIcon = typedArray.getInt(R.styleable.customButtonViewAttrs_drawableIcon,0);
title = typedArray.getString(R.styleable.customButtonViewAttrs_title);
description = typedArray.getString(R.styleable.customButtonViewAttrs_description);
typedArray.recycle();
init();
}
public void init() {
if (isInEditMode())
return;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.custom_button_view, null);
iconImgV = (ImageView) myView.findViewById(R.id.iconImgV);
titleTv = (TextView) myView.findViewById(R.id.titleTv);
descriptionTv = (TextView) myView.findViewById(R.id.descriptionTv);
titleTv.setText(title);
addView(myView);
}
}
and value/attrs.xml
<declare-styleable name="customButtonViewAttrs">
<attr name="title" format="string" />
<attr name="description" format="string" />
<attr name="drawableIcon" format="integer" />
</declare-styleable>
you can use this way
<com.example.rasoul.testprojectstacj.CustomButtonView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:title = "Car"/>
Found a solution, widget.newTable does this perfectly

Android popup won't dismiss

I am trying to implement a popup in my application but it won't dismiss. The Popup is supposed to open when I click on a Plus button, and this works. However, it is supposed to close when I click on the Cancel button in popup layout but it doesn't. why?
Popup layout (tempo_popup.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/confirmtempo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Confirm" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/canceltempo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Cancel" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Java code:
public class MetronomeActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_metronome);
final Button plus = (Button) findViewById(R.id.tempop);
final Button minus = (Button) findViewById(R.id.tempom);
final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pop = inflater.inflate(R.layout.tempo_popup, null, false);
final PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.tempo_popup, null, false),
250, 150, true);
// The code below assumes that the root container has an id called 'main'
pw.showAtLocation(plus, Gravity.CENTER, 0, 0);
Button cancel_tempo = (Button) pop.findViewById(R.id.canceltempo);
cancel_tempo.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Begin1", "POPUP CANCEL");
pw.dismiss();
}
});
}
});
}
}
Damn it! Replace single line of code, it will work like charm.
Instead:
PopupWindow popUpWindow = new PopupWindow(inflater.inflate(R.layout.tempo_popup, null, false),250, 150, true);
Use:
View view = inflater.inflate(R.layout.tempo_popup, null, false);
PopupWindow popUpWindow = new PopupWindow(view, 250, 150, true);
Does the Popup cancel log get printed? Otherwise this might help:
Android popup window dismissal

Resources