schemas | #Frontend Framework | A repository of Open mHealth schemas.

 by   openmhealth Java Updated: 11 months ago - v1.2.1 License: Apache-2.0

Download this library from

Build Applications

kandi X-RAY | schemas REVIEW AND RATINGS

The schemas are located in the schema directory.

kandi-support
Support

  • schemas has a low active ecosystem.
  • It has 60 star(s) with 40 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 46 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • schemas has no issues reported.

security
Security

  • schemas has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

license
License

  • schemas is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.

build
Reuse

  • schemas releases are available to install and integrate.
  • Deployable package is available in npm.
  • Build file is available. You can build the component from source.
Top functions reviewed by kandi - BETA

kandi has reviewed schemas and discovered the below as its top functions. This is intended to give you an instant insight into schemas implemented functionality, and help decide if they suit your requirements.

  • Compares two SchemaVersion objects
  • Returns a new instance of the Jackson ObjectMapper
  • Checks if the given object is equal to the given object .
  • Compares two sleep duration objects .
  • Serializes an OffsetDateTime to JSON .
  • Creates a time interval with the specified start date and end dates .
  • Gets the additional properties .
  • Get typed unit
  • Gets the schema schema id .
  • Gets the schema ID .

schemas Key Features

A repository of Open mHealth schemas.

schemas examples and code snippets

  • Meson / Ninja build system - How to run custom script at Uninstall?
  • Parsing XML using Python and create an excel report - Elementree/lxml
  • MVVM WPF - How to update DataGrid bound to ObservableCollection
  • collapsingtoolbarlayout recyclerview working separately
  • Dropdown in custom Alertdialog doesn't show any items (Kotlin)
  • Android RecyclerView on a null object reference
  • Negative Margins For RecyclerView Item Decoration
  • Change the Statusbar text color to black when the Statusbar background is white
  • Android studio widgets get disappeared in Relative layout
  • Unable to properly Transform nested array with JOLT

Meson / Ninja build system - How to run custom script at Uninstall?

 run_target('my-uninstall', command : ['scripts/uninstall.sh'])

Parsing XML using Python and create an excel report - Elementree/lxml

path = "/TestReports_Backup"

def proc_xml(file_path):
    tree = etree.parse(os.path.join(path, file_path))
    
    data = [
       { **n.attrib, 
         **{el.tag: el.text.strip() for el in n.xpath("*")}
       } for n in tree.xpath("//testcase")
    ]
        
    return pd.DataFrame(data)
    
df_reports = pd.concat([
    proc_xml(f) 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])
path = "/TestReports_Backup"

df_reports = pd.concat([
    pd.read_xml(os.path.join(path, f), xpath="//testcase") 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])
-----------------------
path = "/TestReports_Backup"

def proc_xml(file_path):
    tree = etree.parse(os.path.join(path, file_path))
    
    data = [
       { **n.attrib, 
         **{el.tag: el.text.strip() for el in n.xpath("*")}
       } for n in tree.xpath("//testcase")
    ]
        
    return pd.DataFrame(data)
    
df_reports = pd.concat([
    proc_xml(f) 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])
path = "/TestReports_Backup"

df_reports = pd.concat([
    pd.read_xml(os.path.join(path, f), xpath="//testcase") 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])

MVVM WPF - How to update DataGrid bound to ObservableCollection

public ObservableCollection<LicenseHolders> licenseHolders { get; }
        = new ObservableCollection<LicenseHolders>();
-----------------------
        private bool RemoveFromBD(LicenseHolders license)
        {
            string sql = string.Format("Delete from tblLicenseHolder where ID = '{0}'", license.ID);
            using (SqlConnection sqlCon = new SqlConnection(ConnectionString.connectionString))
            using (SqlCommand cmd = new SqlCommand(sql, sqlCon))
            {
                try
                {
                    sqlCon.Open();
                    cmd.ExecuteNonQuery();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

collapsingtoolbarlayout recyclerview working separately

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/itineraryListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:windowBackground">
    
    
    <androidx.coordinatorlayout.widget.CoordinatorLayout 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">
        
        
        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true">
            
            
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways">
                
                
                <Button
                    android:id="@+id/button_arrow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="@dimen/_20sdp"
                    android:layout_marginEnd="@dimen/activity_end_margin"
                    android:background="@null"
                    android:clickable="true"
                    android:drawableStart="@drawable/ic_arrow_booking_details"
                    android:gravity="start|center_vertical" />
                
                
                <ImageView
                    android:id="@+id/iv_background_image"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/_123sdp"
                    android:contentDescription="@string/name_app"
                    android:scaleType="centerCrop"
                    app:srcCompat="@drawable/booking_details_background" />
                
                
                <ImageView
                    android:id="@+id/iv_background_rectangle"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/_123sdp"
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax"
                    app:srcCompat="@drawable/rectangle_booking_details" />
                
                
                <TextView
                    android:id="@+id/tv_background_title"
                    style="@style/font_title_bookingdetails"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="95dp"
                    android:layout_marginEnd="@dimen/activity_end_margin"
                    android:gravity="start|center_vertical"
                    android:text="@string/text_trek_everest_name"
                    android:textColor="@color/colorPrimary" />
                
                
                <androidx.constraintlayout.widget.Guideline
                    android:id="@+id/guideline9"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    app:layout_constraintGuide_begin="26dp" />
                
                
                <androidx.appcompat.widget.Toolbar
                    android:layout_width="?attr/actionBarSize"
                    android:layout_height="wrap_content"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
            
            
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        
        
        </com.google.android.material.appbar.AppBarLayout>
        
        
        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                
                <TextView
                    android:id="@+id/tv_title_itinerary_list"
                    style="@style/font_title_day1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:layout_marginBottom="@dimen/activity_end_margin"
                    
                    android:gravity="center_vertical"
                    android:text="@string/dashboard_itinerary"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintVertical_bias="0.235" />
                
                <include layout="@layout/booking_itinerary_recyclerview" />
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</FrameLayout>

Dropdown in custom Alertdialog doesn't show any items (Kotlin)

// inflate your layout    
val dialogView = LayoutInflater.from(this).inflate(R.layout.pizza_alert_dialog, null, false)
     
// and set it as dialog view          
pizzaDialogBuilder.setView(dialogView)
    
// then call findViewById on this ViewGroup to get the Spinner            
val pizzaDropdown = dialogView.findViewById<Spinner>(R.id.pizzaSelection)

Android RecyclerView on a null object reference

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Negative Margins For RecyclerView Item Decoration

<?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="wrap_content"
    android:layout_marginBottom="-20dp"
    android:background="@android:color/transparent">


    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cvTop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:outlineProvider="none"
            app:backgroundTint="@android:color/transparent"
            app:layout_anchor="@id/navigation" />

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="bottom"
            android:layout_marginStart="8dp"
            android:layout_marginTop="2dp"
            android:layout_marginEnd="8dp"
            app:backgroundTint="@android:color/holo_blue_dark">

        </com.google.android.material.bottomappbar.BottomAppBar>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundTint="@color/fab_green"
        app:layout_constraintBottom_toBottomOf="@+id/cvTop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cvTop" />

    <TextView
        android:id="@+id/tv_item_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Item No. 0" />

</androidx.constraintlayout.widget.ConstraintLayout>
-----------------------
mRecycler.setChildDrawingOrderCallback(new RecyclerView.ChildDrawingOrderCallback() {
    @Override
    public int onGetChildDrawingOrder(int childCount, int i) {
        return childCount - i - 1;
    }
});
class OverlapItemDecoration(context: Context, overlapDp: Int) : RecyclerView.ItemDecoration() {

    private val overlapPx: Int

    init {
        overlapPx = (context.resources.displayMetrics.density * overlapDp.toFloat()).toInt()
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        if (parent.getChildAdapterPosition(view) == 0) return
        outRect.set(0, overlapPx, 0, 0)
    }
}
-----------------------
mRecycler.setChildDrawingOrderCallback(new RecyclerView.ChildDrawingOrderCallback() {
    @Override
    public int onGetChildDrawingOrder(int childCount, int i) {
        return childCount - i - 1;
    }
});
class OverlapItemDecoration(context: Context, overlapDp: Int) : RecyclerView.ItemDecoration() {

    private val overlapPx: Int

    init {
        overlapPx = (context.resources.displayMetrics.density * overlapDp.toFloat()).toInt()
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        if (parent.getChildAdapterPosition(view) == 0) return
        outRect.set(0, overlapPx, 0, 0)
    }
}

Change the Statusbar text color to black when the Statusbar background is white

<item name="android:windowLightStatusBar">true</item>
<item name="android:statusBarColor">@color/white</item>

Android studio widgets get disappeared in Relative layout

android:layout_above="@+id/editTextemail"
-----------------------
android:layout_above="@+id/editTextemail"
android:layout_below="@+id/imageView"
-----------------------
android:layout_above="@+id/editTextemail"
android:layout_below="@+id/imageView"

Unable to properly Transform nested array with JOLT

 [
      {
        "operation": "shift",
        "spec": {
          "rows": {
            "*": {
              "content": {
                "name": {
                  "content": "[].name"
                },
                "schemaExtensions": {
                  "content": {
                    "*": {
                      "content": {
                        "schema": {
                          "content": "[&7].schemaExtensions[&7].schema"
                        },
                        "required": {
                          "content": "[&7].schemaExtensions[&7].required"
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        }
    ]
-----------------------
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "name": { "*": "&1" },
            "schemaExtensions": {
              "*": {
                "*": { "*": { "*": { "*": "&5.&1" } } }
              }
            }
          }
        }
      }
    }
  }
]

COMMUNITY DISCUSSIONS

Top Trending Discussions on schemas
  • Save Outlook Mailitem to local folder
  • Meson / Ninja build system - How to run custom script at Uninstall?
  • Parsing XML using Python and create an excel report - Elementree/lxml
  • MVVM WPF - How to update DataGrid bound to ObservableCollection
  • collapsingtoolbarlayout recyclerview working separately
  • Dropdown in custom Alertdialog doesn't show any items (Kotlin)
  • Android RecyclerView on a null object reference
  • How can i solve this error in android studio? java.lang.IllegalStateException: Required view 'recycler_food_list'
  • Negative Margins For RecyclerView Item Decoration
  • Change the Statusbar text color to black when the Statusbar background is white
Top Trending Discussions on schemas

QUESTION

Save Outlook Mailitem to local folder

Asked 2021-Jun-15 at 19:38

The following code does everything I want: pulls email, saves attachments, extracts files EXCEPT save the original email to the folder fDest. I seem unable to see the solution.

This seems to be the problematic line as it won't save the email: "mi.SaveAs fDest2, olMSG"

Sub SaveAttachments()
    Dim ol As Outlook.Application
    Dim ns As Outlook.Namespace
    Dim fol As Outlook.Folder
    Dim i As Object
    Dim mi As Outlook.MailItem
    Dim at As Outlook.Attachment
    Dim Inbox As MAPIFolder
    Dim strDate As String
    Dim oApp As Object
    Dim fDest As Variant
    Dim j As Variant
    Dim sh As String
    Dim FileDialog As FileDialog
    Dim Tracker As Workbook
    Dim fSheet As Sheets
    Dim LastRow As Long
    Dim strFilePath
    Dim fTracker As Workbook
               
    strDate = InputBox("Enter Date in format dd-Mmm-yyyy", "User Date", Format(Now(), "dd-Mmm-yyyy"))
    strFilePath = "\\namdfs\CARDS\MWD\GROUPS\GCM_NAM\2021\05 May\"
    fTrackerName = "Inquiry.Tracker.SWPA.Violations.May.2021.xlsx" '

    On Error Resume Next
        Set fTracker = Workbooks(fTrackerName)
        'If Err Then Set fTracker = Workbooks.Open(strFilePath & fTrackerName)
    On Error GoTo 0
        'Windows(fTrackerName).Activate
      
    Set ol = New Outlook.Application
    Set ns = ol.GetNamespace("MAPI")
    Set fol = ns.Folders("GCMNamLogs").Folders("Inbox")
        
    fDest = "C:\Users\jb76991\Desktop\Violations_Emails\"
    fUser = UCase(Environ("username")) & ":" & Chr(10) & Now()
        
    For Each i In fol.Items.Restrict("@SQL=urn:schemas:httpmail:subject LIKE '%" & strDate & "%'")
        'Debug.Print fDest & i & ".msg"
        If i.Class = olMail Then
            Set mi = i
            fDest2 = fDest & mi.Subject & ".msg"
            mi.SaveAs fDest2, olMSG
            For Each at In mi.Attachments
                'do something with attachments but i've commented it out
            Next at
        End If
    Next i
    MsgBox ("Completed")
    
End Sub

Can anyone tell me how to save the original emails that are being filtered?

ANSWER

Answered 2021-Jun-15 at 19:38

You must be sure there are no invalid characters in the filename. See What characters are forbidden in Windows and Linux directory names? for more information. So, I'd suggest using the Replace method available in VBA before passing anything to the SaveAs method.

Another point is that you need to specify unique file names to each email. Make sure the generated file name is unique for a folder.

Source https://stackoverflow.com/questions/67990552

QUESTION

Meson / Ninja build system - How to run custom script at Uninstall?

Asked 2021-Jun-15 at 18:46

Meson/Ninja provide an easy method to run a script at install time.
For example, this line will tell Meson to run the glib-compile-schemas command to compile the GSettings on Linux (system configuration options).

meson.add_install_script('glib-compile-schemas', schemas_dir)
(this command will be automatically run when the user executes ninja install)

How can I tell Meson to run a custom command at uninstall?
In this specific case I would like to delete (or at least reset to default) the key-value pairs in GSettings. To reset them, I have found that the command is gsettings reset-recursively <path> (successfully tested in terminal).

ANSWER

Answered 2021-Jun-15 at 18:46

Adding custom uninstall script is still being discussed, it's proposed quite some time ago but not yet implemented. It looks this task is typically left for package manager (and therefore to corresponding packaged scripts).

But I agree, there is some illogical asymmetry in case of meson install command. As a workaround, you can create your own target:

 run_target('my-uninstall', command : ['scripts/uninstall.sh'])

The drawbacks, of course, are that it should be invoked explicitly, cannot override, append or rename internal uninstall target and script should have executable permissions.

The internal, reserved uninstall target, however, does revert all explicit install operations:

Meson allows you to uninstall an install step by invoking the uninstall target. This will remove all files installed as part of install. Note that this does not restore the original files. This also does not undo changes done by custom install scripts (because they can do arbitrary install operations).

Source https://stackoverflow.com/questions/67981130

QUESTION

Parsing XML using Python and create an excel report - Elementree/lxml

Asked 2021-Jun-15 at 17:46

I am trying to parse many XML test results files and get the necessary data like testcase name, test result, failure message etc to an excel format. I decided to go with Python.

My XML file is a huge file and the format is as follows. The cases which failed has a message, & and the passed ones only has . My requirement is to create an excel with testcasename, test status(pass/fail), test failure message.

<?xml version="1.0" encoding="UTF-8"?>
<testsuites xmlns:a="http://microsoft.com/schemas/VisualStudio/TeamTest/2006"
            xmlns:b="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
  <testsuite name="MSTestSuite" tests="192" time="0" failures="16" errors="0" skipped="0">
    <testcase classname="dfsgsgg" name="Results are displayed" time="27.8096966">
      <failure message="unknown error: jQuery is not defined&#xA;">  
      </failure>
      <system-out>Given the user is on the landing page
      -&gt; error: unknown error: jQuery is not defined
      </system-out>
      <system-err>unknown error: jQuery is not defined          
      </system-err>
    </testcase>
    <testcase classname="dfsgsgg" name="Results are displayed" time="27.8096966">
      <failure message="unknown error: jQuery is not defined&#xA;"> 
      </failure>
      <system-out>Given the user is on the landing page
      -&gt; error: unknown error: jQuery is not defined
      </system-out>
      <system-err>unknown error: jQuery is not defined          
      </system-err>
    </testcase>                                                               
    <testcase classname="dfsgsgg" name="Results are displayed" time="27.8096966">
      <failure message="unknown error: jQuery is not defined&#xA;"> 
      </failure>
      <system-out>Given the user is on the landing page
      -&gt; error: unknown error: jQuery is not defined
      </system-out>
      <system-err>unknown error: jQuery is not defined          
      </system-err>
    </testcase>                                                           
    <testcase classname="dfsgsgg" name="Results are displayed" time="27.8096966">
      <system-out>Given the user is on the landing page
      -&gt; error: unknown error: jQuery is not defined
      </system-out>
    </testcase>
  </testsuite>
</testsuites>

I have come up with the following code. Please bear if there are any basic mistakes as I am very new to this. With this code I can retrieve test case name, class name but I am unable to pick the failure message, system-out and system-err. Though these tags are also part of testcase tag, I am not able to fetch it. Can someone help me through this? Thanks! With only testcase name and class name, I am able to write to an excel.

## Parsing XML files ###

import os
import pandas as pd
from lxml import etree

df_reports = pd.DataFrame()
df = pd.DataFrame()
i = 0
pass_count = 0
fail_count = 0

path = '/TestReports_Backup/'
files = os.listdir(path)
print(len(files))

for file in files:
    file_path = path+file
    print(file_path)
    tree = etree.parse(file_path)
    testcases = tree.xpath('.//testcase')
    systemout = tree.xpath('.//testcase/system-out')
    failure = tree.xpath('.//testcase/failure')

    for testcase in testcases:
        test = {}
        test['TestCaseName'] = testcase.attrib['name']
        test['Classname'] = testcase.attrib['classname']
        test['TestStatus'] = failure.attrib['message']

        df = pd.DataFrame(test, index=[i])
        i = i + 1
        df_reports = pd.concat([df_reports, df])
        print(df_reports)

df.head()
df_reports.to_csv('/TestReports_Backup/Reports.csv')

ANSWER

Answered 2021-Jun-15 at 17:46

Since your XML is relatively flat, consider a list/dictionary comprehension to retrieve all child elements and attrib dictionary. From there, call pd.concat once outside the loop. Below runs a dictionary merge (Python 3.5+).

path = "/TestReports_Backup"

def proc_xml(file_path):
    tree = etree.parse(os.path.join(path, file_path))
    
    data = [
       { **n.attrib, 
         **{el.tag: el.text.strip() for el in n.xpath("*")}
       } for n in tree.xpath("//testcase")
    ]
        
    return pd.DataFrame(data)
    
df_reports = pd.concat([
    proc_xml(f) 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])

Also, starting in Pandas v1.3, there is now an available read_xml (default parser being lxml and defaults to retrieve all attributes and child elements at specific xpath):

path = "/TestReports_Backup"

df_reports = pd.concat([
    pd.read_xml(os.path.join(path, f), xpath="//testcase") 
    for f in os.listdir(path) 
    if f.endswith(".xml")
])

Source https://stackoverflow.com/questions/67977767

QUESTION

MVVM WPF - How to update DataGrid bound to ObservableCollection

Asked 2021-Jun-15 at 17:35

What I'm trying to do:

I have a WPF app, linked to a SQL-server. I am using the MVVM-light package (I do actually have Prism.Core installed, but I'm not sure if I'm using it or not.... new to MVVM).

There's a DataGrid, bound to an ObservableCollection. I have been trying to implement the PropertyChangedEventHandler, but I can't seem to get it to work.

I have a Delete button bound, and I am able to remove rows, but when I re-open the form, the changes does not carry over.

I tried to change the binding-mode for the DataGrid from OneWay to TwoWay. With OneWay, the changes does not carry over when I re-open the form. With TwoWay, I get this error message when opening the child form (which contains the DataGrid):

System.InvalidOperationException: 'A TwoWay or OneWayToSource binding cannot work on the read->only property 'licenseHolders' of type 'Ridel.Hub.ViewModel.LicenseHoldersViewModel'.'

So, If I then add a set; to my public ObservableCollection<LicenseHolders> licenseHolders { get; }, the program runs, but the previous problem persists, like it did when there was a OneWay mode configuration on the DataGrid.

What do I need to do to get this to work without communicating directly with the Sql-server, which would defy the whole point of using this methodology in the first place?

ViewModel:

public class LicenseHoldersViewModel : INotifyPropertyChanged {

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<LicenseHolders> licenseHolders { get; }
        = new ObservableCollection<LicenseHolders>();

    public LicenseHoldersViewModel() {

        FillDataGridLicenseHolders();
    }

    private void FillDataGridLicenseHolders() {

        try {

            using (SqlConnection sqlCon = new(ConnectionString.connectionString))
            using (SqlCommand sqlCmd = new("select * from tblLicenseHolder", sqlCon))
            using (SqlDataAdapter sqlDaAd = new(sqlCmd))
            using (DataSet ds = new()) {

                sqlCon.Open();
                sqlDaAd.Fill(ds, "tblLicenseHolder");

                foreach (DataRow dr in ds.Tables[0].Rows) {

                    licenseHolders.Add(new LicenseHolders {

                        ID = Convert.ToInt32(dr[0].ToString()),
                        Foretaksnavn = dr[1].ToString(),
                        Foretaksnummer = dr[2].ToString(),
                        Adresse = dr[3].ToString(),
                        Postnummer = (int)dr[4],
                        Poststed = dr[5].ToString(),
                        BIC = dr[6].ToString(),
                        IBAN = dr[7].ToString(),
                        //Profilbilde ???
                        Kontaktperson = dr[8].ToString(),
                        Epost = dr[9].ToString(),
                        Tlf = dr[10].ToString()
                    });
                }
            }

        } catch (Exception ex) {

            MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }

    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHoldersCommand => _removeLicenseHoldersCommand
        ??= new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);

    private bool RemoveLicenseHolderCanExecute(LicenseHolders myLicenseHolder) {

        // Checking for the removeable licenseholder in the collection
        return licenseHolders.Contains(myLicenseHolder);
    }

    private void RemoveLicenseHolderExecute(LicenseHolders myLicenseHolder) {

        licenseHolders.Remove(myLicenseHolder);
    }

    private void OnPropertyChanged(string myLicenseHolder) {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(myLicenseHolder));
    }
}

Model

public class LicenseHolders {

    public int ID { get; set; }
    public string Foretaksnavn { get; set; }
    public string Foretaksnummer { get; set; }
    public string Adresse { get; set; }
    public int Postnummer { get; set; }
    public string Poststed { get; set; }
    public string BIC { get; set; }
    public string IBAN { get; set; }
    public string Kontaktperson { get; set; }
    public string Epost { get; set; }
    public string Tlf { get; set; }

}

Code-behind

public partial class Personell : Window {

        LicenseHoldersViewModel licenseHoldersViewModel;

        public Personell() {

            InitializeComponent();
            btnLogOut.Content = UserInfo.UserName;

            licenseHoldersViewModel = new LicenseHoldersViewModel();
            base.DataContext = licenseHoldersViewModel;
        }

XAML

<Window x:Class="Ridel.Hub.Personell"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Ridel.Hub" xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel" d:DataContext="{d:DesignInstance Type=viewmodel:LicenseHoldersViewModel}"
        mc:Ignorable="d"
        
    <Canvas Margin="10,10,10,10">
    <!-- I click this button when I want to delete a DataGrid row -->
        <Button Style="{DynamicResource ButtonWithRoundCornersGreen}" FontSize="22" x:Name="btnDelete" Content="Delete license holder" Width="187" Height="47" 
                Background="#48bb88" Foreground="White" Canvas.Left="547" Canvas.Top="668" IsEnabled="False" 
                Command="{Binding RemoveLicenseHoldersCommand}" CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>

        <DataGrid             
            x:Name="dgLicenseHolder"
            CanUserAddRows="False"
            ItemsSource="{Binding licenseHolders, Mode=TwoWay}"
            Height="557" 
            Width="505" 
            ColumnWidth="*"
            Canvas.Top="158" 
            FontSize="20"
            IsReadOnly="True"
            SelectionMode="Single"
            AutoGenerateColumns="False"
            CanUserDeleteRows="False"          
            SelectionChanged="dgLicenseHolder_SelectionChanged" Canvas.Left="31" >

            <DataGrid.Columns>
                <DataGridTextColumn Header="ID"             Binding="{Binding Path='ID'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Foretaksnavn"   Binding="{Binding Path='Foretaksnavn'}" IsReadOnly="True" Visibility="Visible"/>
                <DataGridTextColumn Header="Foretaksnummer" Binding="{Binding Path='Foretaksnummer'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Adresse"        Binding="{Binding Path='Adresse'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Postnummer"     Binding="{Binding Path='Postnummer'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Poststed"       Binding="{Binding Path='Poststed'}" IsReadOnly="True" Visibility="Visible"/>
                <DataGridTextColumn Header="BIC"            Binding="{Binding Path='BIC'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="IBAN"           Binding="{Binding Path='IBAN'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Kontaktperson"  Binding="{Binding Path='Kontaktperson'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Epost"          Binding="{Binding Path='Epost'}" IsReadOnly="True" Visibility="Collapsed"/>
                <DataGridTextColumn Header="Tlf"            Binding="{Binding Path='Tlf'}" IsReadOnly="True" Visibility="Collapsed"/>
            </DataGrid.Columns>
            
        </DataGrid>
    </Canvas>
</Window>

ANSWER

Answered 2021-Jun-15 at 13:26

You are confusing topics. The VM needs InotifyPropertyChanged events, which you have but are not using, to notify the Xaml in the front-end that a VMs property has changed and to bind to the new data reference.

This is needed for Lists or ObservableCollections. Once that is done, the ObservableCollection will then send notifications on changes to the list as items are added or removed.

Because you miss the first step:

public ObservableCollection<LicenseHolders> licenseHolders { get; }
        = new ObservableCollection<LicenseHolders>();

the front end does not get the reference change. Because it does not have a set { _myCollection = value; OnPropertyChanged( "licenseHolders "); }

the Xaml does not know to change the binding from the initial null to a valid reference to a list and you get a non-working visual control.


Frankly if you are not paging the information (adding or removing to the ObservableCollection after the initial run), the ObservableCollection can be replaced by a simple List...just add the rows to a valid local variables list, and at the very end then set it to be licenseHolders list and the front end xaml will work.

Source https://stackoverflow.com/questions/67986693

QUESTION

collapsingtoolbarlayout recyclerview working separately

Asked 2021-Jun-15 at 16:32

Collapsing toolbar layout and the recycler view should work together while swiping but working separately. suggest to me what to do! given below are my code and resulting gif part of my project.

the toolbar layout is not showing fully if I swipe the screen from bottom to top. the toolbar layout is closed and only return if I swipe to toolbar layout separately.

i want to toolbar layout to be in the same manner when i swipe the screen up and down.

Code of my layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".ui.review.reviewActivity">


    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">


        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collaps_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="true">


            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:gravity="center_vertical"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:contentDescription="TODO"
                    android:src="@drawable/cover_image"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_collapseMode="parallax">

                <TextView
                    android:id="@+id/textView_title"
                    android:layout_width="wrap_content"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="130dp"
                    android:gravity="center"
                    android:maxLines="1"
                    android:text="title"
                    android:textColor="#FFF"
                    android:textSize="24sp" />

            </FrameLayout>

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:theme="@style/Theme.AppTheme.PopupOverlay"
                app:layout_collapseMode="parallax" />


        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/review_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fadeScrollbars="false"
            android:scrollbars="vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Final result

enter image description here

ANSWER

Answered 2021-Jun-15 at 16:32

Try this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/itineraryListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:windowBackground">
    
    
    <androidx.coordinatorlayout.widget.CoordinatorLayout 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">
        
        
        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true">
            
            
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways">
                
                
                <Button
                    android:id="@+id/button_arrow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="@dimen/_20sdp"
                    android:layout_marginEnd="@dimen/activity_end_margin"
                    android:background="@null"
                    android:clickable="true"
                    android:drawableStart="@drawable/ic_arrow_booking_details"
                    android:gravity="start|center_vertical" />
                
                
                <ImageView
                    android:id="@+id/iv_background_image"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/_123sdp"
                    android:contentDescription="@string/name_app"
                    android:scaleType="centerCrop"
                    app:srcCompat="@drawable/booking_details_background" />
                
                
                <ImageView
                    android:id="@+id/iv_background_rectangle"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/_123sdp"
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax"
                    app:srcCompat="@drawable/rectangle_booking_details" />
                
                
                <TextView
                    android:id="@+id/tv_background_title"
                    style="@style/font_title_bookingdetails"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="95dp"
                    android:layout_marginEnd="@dimen/activity_end_margin"
                    android:gravity="start|center_vertical"
                    android:text="@string/text_trek_everest_name"
                    android:textColor="@color/colorPrimary" />
                
                
                <androidx.constraintlayout.widget.Guideline
                    android:id="@+id/guideline9"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    app:layout_constraintGuide_begin="26dp" />
                
                
                <androidx.appcompat.widget.Toolbar
                    android:layout_width="?attr/actionBarSize"
                    android:layout_height="wrap_content"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
            
            
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        
        
        </com.google.android.material.appbar.AppBarLayout>
        
        
        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                
                <TextView
                    android:id="@+id/tv_title_itinerary_list"
                    style="@style/font_title_day1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/activity_start_margin"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:layout_marginBottom="@dimen/activity_end_margin"
                    
                    android:gravity="center_vertical"
                    android:text="@string/dashboard_itinerary"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintVertical_bias="0.235" />
                
                <include layout="@layout/booking_itinerary_recyclerview" />
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</FrameLayout>

This is the output of this code.

enter image description here

Source https://stackoverflow.com/questions/67981602

QUESTION

Dropdown in custom Alertdialog doesn't show any items (Kotlin)

Asked 2021-Jun-15 at 12:10

I wanted to create a custom Alertdialog Layout with a dropdown list and a few other things. I'm using Kotlin and I'm pretty new to it Currently I'm stuck at the dropdown list as it doesn't show anything

Here is the Layout.xml:

    <?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">

    <Button
        android:id="@+id/backButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:text="Zurück"
        app:icon="@drawable/ic_baseline_arrow_back_24"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/pizzaSelection"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

And here is how I call up the dialog in my activity:

   private fun showPizzaDialog(){
        val pizzaDialogBuilder = AlertDialog.Builder(this)
        pizzaDialogBuilder.setView(R.layout.pizza_alertdialog)
        
        val pizzaDropdown = findViewById<Spinner>(R.id.pizzaSelection)
        val pizzaTypes = resources.getStringArray(R.array.pizzaTypes)

        if (pizzaDropdown != null) {
            val adapter = ArrayAdapter(this,
                android.R.layout.simple_spinner_item, pizzaTypes)
            pizzaDropdown.adapter = adapter
        }
        
        pizzaDialogBuilder.show()

    }

The Items are currently hardcoded in the strings.xml resource file as a string-array.

The AlertDialog shows up and i can see and click on the arrow for the dropdown menu, but when I click on it nothing happens.

ANSWER

Answered 2021-Jun-15 at 12:10

You're calling findViewById on your current Activity, which doesn't contain R.id.pizza_selection. Therefore I suspect you'll see

val pizzaDropdown = findViewById<Spinner>(R.id.pizzaSelection)

return null.

Try something like this:

// inflate your layout    
val dialogView = LayoutInflater.from(this).inflate(R.layout.pizza_alert_dialog, null, false)
     
// and set it as dialog view          
pizzaDialogBuilder.setView(dialogView)
    
// then call findViewById on this ViewGroup to get the Spinner            
val pizzaDropdown = dialogView.findViewById<Spinner>(R.id.pizzaSelection)

my Kotlin syntax might not be correct, sorry. Important is that we're calling findViewById on dialogView, instead of the implicit this.findViewById()

Source https://stackoverflow.com/questions/67985476

QUESTION

Android RecyclerView on a null object reference

Asked 2021-Jun-15 at 11:00

im trying to get Highscores from a File and display them in a RecyclerView. But im getting the following Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.ausbaustufe1.CustomAdapter.onBindViewHolder(CustomAdapter.java:46)
        at com.example.ausbaustufe1.CustomAdapter.onBindViewHolder(CustomAdapter.java:16)

I know that my scoreItems in

CustomAdapter adapter = new CustomAdapter(scoreItems); 

arent empty. I dont know what i am doing wrong. I´m new in the Android World :)

Thanks for helping.

My files: score_activity.java

public class score_activty extends AppCompatActivity {
    ArrayList<ScoreItem> scoreItems;
    FileIOScores io = new FileIOScores(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_activty);
        RecyclerView rvItems = findViewById(R.id.recview);
        scoreItems = io.readScores("file1.txt");
        Log.v("mytag",scoreItems.toString());
        CustomAdapter adapter = new CustomAdapter(scoreItems);
        Log.v("mytag",String.valueOf(adapter.getItemCount()));
        rvItems.setLayoutManager(new LinearLayoutManager(this));
        rvItems.setAdapter(adapter);

    }
}

CustomAdapter.java

package com.example.ausbaustufe1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private TextView textView;
    private List<ScoreItem> scores;

    public CustomAdapter(ArrayList<ScoreItem> scoreItems) {
        this.scores = scoreItems;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View scoreView = inflater.inflate(R.layout.recycler_style, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(scoreView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ScoreItem scoreItem = scores.get(position);

        // Set item views based on your views and data model
        TextView textView = holder.textView;
        textView.setText(scoreItem.toString());


    }

    @Override
    public int getItemCount() {
        return scores.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;
        private List<ScoreItem> scores;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView);
        }

        public TextView getTextView() {
            return textView;
        }
        public void CustomAdapter(List<ScoreItem> scores){

            this.scores = scores;
        }





    }
}

activity_score_activity.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"
    tools:context=".score_activty">

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/clr"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="-2dp" />
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        />
</LinearLayout>

recycler_style.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">
    <TextView
        android:layout_width="@+id/textView"
        android:layout_height="wrap_content"
        />

</LinearLayout>

ANSWER

Answered 2021-Jun-15 at 11:00

You mistype the recycler_style.xml, the id must be specified in the android:id property and not in android:layout_width

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Source https://stackoverflow.com/questions/67984846

QUESTION

How can i solve this error in android studio? java.lang.IllegalStateException: Required view 'recycler_food_list'

Asked 2021-Jun-15 at 04:33

I'm new to android studio and i'm not sure what was going on with it. How can I solve this error?

In the logcat, it mentioned that I required a view for recycler_food_list which apparently I had already coded into the foodlistfragment.java.

Logcat

2021-06-15 11:11:57.189 5164-5164/com.android.ridefun E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.ridefun, PID: 5164
java.lang.IllegalStateException: Required view 'recycler_food_list' with ID 2131231048 for field 'recycler_food_list' was not found. If this view is optional add '@Nullable' (fields) or '@Optional' (methods) annotation.
    at butterknife.internal.Utils.findRequiredView(Utils.java:84)
    at butterknife.internal.Utils.findRequiredViewAsType(Utils.java:96)
    at com.android.ridefun.ui.foodlist.FoodListFragment_ViewBinding.<init>(FoodListFragment_ViewBinding.java:21)
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
    at butterknife.ButterKnife.bind(ButterKnife.java:170)
    at com.android.ridefun.ui.foodlist.FoodListFragment.onCreateView(FoodListFragment.java:44)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

fragment_food_list.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">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_food_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

layout_food_item

<?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="200dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginBottom="8dp"
app:cardCornerRadius="0dp"
app:cardElevation="10dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/img_food_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#AA333639"
        android:orientation="horizontal"
        android:padding="10dp"
        android:weightSum="10">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_food_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Name of food"
            android:textSize="20sp"
            android:textColor="@color/white"/>

        <TextView
            android:id="@+id/txt_food_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="$0"
            android:textSize="20sp"
            android:textColor="@color/white"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="2"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:weightSum="2">

        <ImageView
            android:id="@+id/img_fav"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_baseline_favorite_border_24"
            app:tint="@color/white"/>

        <ImageView
            android:id="@+id/img_quick_cart"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_baseline_shopping_cart_24"
            app:tint="@color/white"/>

    </LinearLayout>

    </LinearLayout>


</RelativeLayout>

</androidx.cardview.widget.CardView>

FoodListFragment.java

public class FoodListFragment extends Fragment {

private FoodListViewModel sendViewModel;

Unbinder unbinder ;
@BindView(R.id.recycler_food_list)
RecyclerView recycler_food_list;

LayoutAnimationController layoutAnimationController;
MyFoodListAdapter adapter;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    sendViewModel =
            new ViewModelProvider(this).get(FoodListViewModel.class);
    View root = inflater.inflate(R.layout.fragment_menu, container, false);
    unbinder = ButterKnife.bind(this,root);
    initViews();
    sendViewModel.getMutableLiveDataFoodList().observe(getViewLifecycleOwner(), foodModels -> {
        adapter = new MyFoodListAdapter(getContext(),foodModels);
        recycler_food_list.setAdapter(adapter);
        recycler_food_list.setLayoutAnimation(layoutAnimationController);
    });
    return root;
}

private void initViews() {
    recycler_food_list.setHasFixedSize(true);
    recycler_food_list.setLayoutManager(new LinearLayoutManager(getContext()));

    layoutAnimationController = AnimationUtils.loadLayoutAnimation(getContext(),R.anim.layout_item_from_left);
}

MyFoodListAdapter

public class MyFoodListAdapter extends RecyclerView.Adapter<MyFoodListAdapter.MyViewHolder> {

private Context context;
private List<FoodModel> foodModelList;

public MyFoodListAdapter(Context context, List<FoodModel> foodModelList) {
    this.context = context;
    this.foodModelList = foodModelList;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new MyViewHolder(LayoutInflater.from(context)
    .inflate(R.layout.layout_food_item,parent,false));
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    Glide.with(context).load(foodModelList.get(position).getImage()).into(holder.img_food_image);
    holder.txt_food_price.setText(new StringBuilder("$")
    .append(foodModelList.get(position).getPrice()));
    holder.txt_food_name.setText(new StringBuilder("")
    .append(foodModelList.get(position).getName()));
}

@Override
public int getItemCount() {
    return foodModelList.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    private Unbinder unbinder;
    @BindView(R.id.txt_food_name)
    TextView txt_food_name;
    @BindView(R.id.txt_food_price)
    TextView txt_food_price;
    @BindView(R.id.img_food_image)
    ImageView img_food_image;
    @BindView(R.id.img_fav)
    ImageView img_fav;
    @BindView(R.id.img_quick_cart)
    ImageView img_cart;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        unbinder = ButterKnife.bind(this,itemView);
    }
}

ANSWER

Answered 2021-Jun-15 at 03:29

You're doing inflater.inflate(R.layout.fragment_menu, container, false);, not inflating your R.layout.fragment_food_list. You'll need to inflate the right layout to find your Recycler view.

Source https://stackoverflow.com/questions/67979583

QUESTION

Negative Margins For RecyclerView Item Decoration

Asked 2021-Jun-14 at 22:01

I need to implement the below layout for my RecyclerView Items (The picture represents two rows):

enter image description here

This is my XML file:

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/theme_primary_color">

    <View
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/half_circle"
        android:translationZ="3dp"
        app:layout_constraintBottom_toTopOf="@id/cvTop"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/cvTop" />

    <androidx.cardview.widget.CardView
        android:id="@+id/cvTop"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="2dp"
        android:layout_marginEnd="8dp"
        app:cardCornerRadius="@dimen/card_view_corner"
        app:layout_constraintTop_toTopOf="parent">

    </androidx.cardview.widget.CardView>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_call"
        app:backgroundTint="@color/fab_green"
        app:fabSize="mini"
        app:layout_constraintBottom_toBottomOf="@+id/cvTop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cvTop" />

</androidx.constraintlayout.widget.ConstraintLayout>

I tried to set negative margins to root ConstraintLayout but the second item went to top of the first one, but I need the first item to be on top of the second one.

ANSWER

Answered 2021-Jun-13 at 03:02

So, this is not exactly what you want but at least it has the same layout as you want with a simpler approach.

So, the main challenges are:

  • Taking a curve cutout on the CardView probably need to be built programmatically with canvas for a better result. But for simplicity, this is replaced by a BottomAppBar wrapped in a CoordinatorLayout in order to have the curve effect with the top circle/gap.

  • Replacing the top View with Fab in order to have an Inset FAB by setting the layout_anchor to the BottomAppBar. Check material design for this.

    And having the cutout behavior requires to make the FAB like it doesn't exist by setting a transparent backgroundTint & removing the outlineProvider

  • Making the top cutout (gap) of a particular row get overlapped to the top row like if it is a part of it. This works with the negative margin on the root view.

<?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="wrap_content"
    android:layout_marginBottom="-20dp"
    android:background="@android:color/transparent">


    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cvTop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:outlineProvider="none"
            app:backgroundTint="@android:color/transparent"
            app:layout_anchor="@id/navigation" />

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_gravity="bottom"
            android:layout_marginStart="8dp"
            android:layout_marginTop="2dp"
            android:layout_marginEnd="8dp"
            app:backgroundTint="@android:color/holo_blue_dark">

        </com.google.android.material.bottomappbar.BottomAppBar>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundTint="@color/fab_green"
        app:layout_constraintBottom_toBottomOf="@+id/cvTop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cvTop" />

    <TextView
        android:id="@+id/tv_item_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Item No. 0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Note: you can remove the TextView, I just added it to check the item doesn't change its position like you had in your case.

Preview on the RecyclerView

enter image description here

UPDATE:

A new challenge:

  • Only the top half of the FAB will intercept touch events, as any particular row will be laid on top of its direct top row; and hence the FAB of the top row won't intercept events in the intersection area.

    Well, this can be manipulated well using canvas & custom View. But also this can be solved in the current approach by laying out the rows of the RecyclerViews from bottom to top. One way to setReverseLayout(true) and then either:

    => Reverse the RecyclerView list positions before submitting to the adapter

    => Or use mList.size - 1 - position instead of position within the adapter. Assuming the list of items is mList

Source https://stackoverflow.com/questions/67902334

QUESTION

Change the Statusbar text color to black when the Statusbar background is white

Asked 2021-Jun-14 at 21:09

I have tried tried a few solutions given here but none seems to work for me. This is what I have in my colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#fcfdfb</color>
    <color name="colorPrimaryDark">#fff</color>
    <color name="colorPrimaryLight">#333</color>
    <color name="colorPrimaryText">#333</color>
    <color name="colorAccent">#000000</color>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
</resources>

And this is what I have in styles.xml

<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@drawable/background_splash</item>
    <item name="android:windowActionBar">false</item>
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@drawable/background_splash</item>
    <item name="android:windowActionBar">false</item>
</style>
<style name="ProDialogue" parent="@android:style/Theme.Dialog">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@color/colorPrimary</item>
    <item name="android:textColor">@color/black</item>
</style>
<style name="TransparentToolbar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <item name="windowActionBarOverlay">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

I just need the Statusbar text/icons to be black because I have the background as white to match the content. As a beginner, I am sure that I've messed it up somewhere but hopefully someone will guide me on this. Btw, my minSdkVersion is 21.

ANSWER

Answered 2021-Jun-14 at 01:11

Add these attributes to your theme

<item name="android:windowLightStatusBar">true</item>
<item name="android:statusBarColor">@color/white</item>

Note this only works on 23+, so you'll have to make a 23+ theme file with these attributes. I'm fairly sure that < 23 every device's status bar is black and white and you can't change that, but you should double check

Source https://stackoverflow.com/questions/67962031

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL schemas

You can use schemas like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the schemas component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement schemas faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi