Re: help me with correction

9 views
Skip to first unread message

Paul Wandendeya

unread,
Nov 13, 2023, 3:59:42 AM11/13/23
to kivy...@googlegroups.com
import re
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView

# List to store nursery pupil information
nursery_pupils = []

class NurseryPupilDatabase(GridLayout):
    def __init__(self, **kwargs):
        super(NurseryPupilDatabase, self).__init__(**kwargs)
        self.cols = 2
        self.spacing = [10, 5]  # Adjusted spacing between widgets

        self.add_widget(Label(text='Name:', size_hint=(0.3, None), height=30))
        self.childname_entry = TextInput(text='Namaranga Ziruna', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.childname_entry)

        self.add_widget(Label(text='Dob:', size_hint=(0.3, None), height=30))
        self.dob_entry = TextInput(text='2021-07-21', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.dob_entry)

        self.add_widget(Label(text='Age:', size_hint=(0.3, None), height=30))
        self.age_entry = TextInput(text='3', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.age_entry)

        self.add_widget(Label(text='Parent Name:', size_hint=(0.3, None), height=30))
        self.parent_entry = TextInput(text='Wandendeya Paul', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.parent_entry)

        self.add_widget(Label(text='Phone Number:', size_hint=(0.3, None), height=30))
        self.phone_entry = TextInput(text='0778161809', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.phone_entry)

        self.add_widget(Label(text='Requirements:', size_hint=(0.3, None), height=30))
        self.requirement_entry = TextInput(text='Special needs', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.requirement_entry)

        self.add_widget(Label(text='School Name:', size_hint=(0.3, None), height=30))
        self.sch_entry = TextInput(text='Wakubona Gad Nursery School', multiline=False, size_hint=(0.7, None), height=30)
        self.add_widget(self.sch_entry)

        self.register_button = Button(text='Register', size_hint=(0.3, None), height=30)
        self.register_button.bind(on_press=self.register_pupil)
        self.add_widget(self.register_button)

        self.display_button = Button(text='Display', size_hint=(0.3, None), height=30)
        self.display_button.bind(on_press=self.display_pupils)
        self.add_widget(self.display_button)

        self.pupil_text = TextInput(readonly=True, size_hint=(1, None), height=150, multiline=True)
        self.add_widget(Label(text='Console:', size_hint=(1, None), height=30))
        self.add_widget(self.pupil_text)

        self.exercises_button = Button(text='Exercises', size_hint=(0.3, None), height=30)
        self.exercises_button.bind(on_press=self.display_exercises)
        self.add_widget(self.exercises_button)

    def register_pupil(self, instance):
        childname = self.childname_entry.text
        dob = self.dob_entry.text
        childage = self.age_entry.text
        parentname = self.parent_entry.text
        phonenumber = self.phone_entry.text
        requirement = self.requirement_entry.text
        sch = self.sch_entry.text

        if childname and childage:
            # Phone number validation
            if not re.match(r'^\d{10}$', phonenumber):
                self.pupil_text.text += "Invalid phone number. Please enter a 10-digit number.\n"
                return

            pupil = {
                "ChildName": childname,
                "Dob": dob,
                "Age": childage,
                "ParentName": parentname,
                "PhoneNumber": phonenumber,
                "Requirements": requirement,
                "SchName": sch
            }
            nursery_pupils.append(pupil)

            self.pupil_text.text += f"ChildName: {childname}, Dob: {dob}, Parent: {parentname}, " \
                                    f"PhoneNumber: {phonenumber}, Requirements: {requirement}, SchName: {sch}\n"
            self.childname_entry.text = ""
            self.dob_entry.text = ""
            self.age_entry.text = ""
            self.parent_entry.text = ""
            self.phone_entry.text = ""
            self.requirement_entry.text = ""
            self.sch_entry.text = ""

            self.pupil_text.text += "Pupil registered successfully!\n"
        else:
            self.pupil_text.text += "Please enter child's name and age.\n"

    def display_pupils(self, instance):
        if nursery_pupils:
            self.pupil_text.text += "List of Nursery Pupils:\n"
            for pupil in nursery_pupils:
                self.pupil_text.text += f"Child Name: {pupil['ChildName']}\n"
                self.pupil_text.text += f"Date of Birth: {pupil['Dob']}\n"
                self.pupil_text.text += f"Age: {pupil['Age']}\n"
                self.pupil_text.text += f"Parent Name: {pupil['ParentName']}\n"
                self.pupil_text.text += f"Phone Number: {pupil['PhoneNumber']}\n"
                self.pupil_text.text += f"Requirements: {pupil['Requirements']}\n"
                self.pupil_text.text += f"School Name: {pupil['SchName']}\n"
                self.pupil_text.text += "------------------------\n"
        else:
            self.pupil_text.text += "No pupils registered yet.\n"

    def display_exercises(self, instance):
        if nursery_pupils:
            self.pupil_text.text += "List of Schools with Subject Marks:\n"
            for pupil in nursery_pupils:
                school_name = pupil['SchName']
                # Assuming you have a dictionary with subject marks for each school
                # Replace `subject_marks` with the actual dictionary
                subject_marks = {
                    "Wakubona Gad Nursery School": {
                        "English": 80,
                        "Mathematics": 75,
                        "Science": 90
                    },
                    # Add more schools and their subject marks here
                }
                if school_name in subject_marks:
                    self.pupil_text.text += f"School Name: {school_name}\n"
                    for subject, mark in subject_marks[school_name].items():
                        self.pupil_text.text += f"{subject}: {mark}\n"
                    self.pupil_text.text += "------------------------\n"
                else:
                    self.pupil_text.text += f"No subject marks available for {school_name}.\n"
        else:
            self.pupil_text.text += "No pupils registered yet.\n"


class NurseryPupilDatabaseApp(App):
    def build(self):
        return NurseryPupilDatabase()


if __name__ == '__main__':
    NurseryPupilDatabaseApp().run()
I'm glad that your a star in kivy development Library. I'm writing to info you that am new here in using kivy library to create a new cross-platform program with kivy...  I tried to write a school database management program above yes the codes are running correctly but producing right results I expected. I expected this to display console beginning from left to right and exercises button have functionality to open a new window with list of school data with Textinput fields can you help me? 

On Wed, Oct 25, 2023, 5:55 PM Дмитро Dmytro <demon...@gmail.com> wrote:

Hi there
How to create Webview with working FileChooser, and how to handle back button to return to main App.
Here is my code, Webview opens, it loads webpage, there is image back button at the browser window but when i press it sometimes it return back to main App, some times it close Webview and main App with only error: #00 pc 00225c74 /data/app/org.test.myapp/lib/arm/libpython3.8.so

File chooser does not work!

`from kivy.uix.modalview import ModalView
from android.runnable import run_on_ui_thread
from jnius import autoclass, cast, PythonJavaClass, java_method, MetaJavaClass

WebViewA = autoclass('android.webkit.WebView')
WebViewClient = autoclass('android.webkit.WebViewClient')
WebChromeClient = autoclass('android.webkit.WebChromeClient')
WebSettings = autoclass('android.webkit.WebSettings')
LayoutParams = autoclass('android.view.ViewGroup$LayoutParams')
ButtonLayoutParams = autoclass('android.widget.FrameLayout$LayoutParams')
LinearLayout = autoclass('android.widget.LinearLayout')
Button = autoclass('android.widget.ImageButton')
KeyEvent = autoclass('android.view.KeyEvent')
ViewGroup = autoclass('android.view.ViewGroup')
DownloadManager = autoclass('android.app.DownloadManager')
DownloadManagerRequest = autoclass('android.app.DownloadManager$Request')
Uri = autoclass('android.net.Uri')
Environment = autoclass('android.os.Environment')
Context = autoclass('android.content.Context')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
View = autoclass('android.view.View')
R = autoclass('android.R$drawable')

OnClickListener = autoclass('android/view/View$OnKeyListener')
HashMap = autoclass('java.util.HashMap')
String = autoclass('java.lang.String')
Color = autoclass('android.graphics.Color')

Intent = autoclass('android.content.Intent')
File = autoclass('java.io.File')

class DownloadListener(PythonJavaClass):
# https://stackoverflow.com/questions/10069050/download-file-inside-webview
javacontext = 'app'
javainterfaces = ['android/webkit/DownloadListener']

@java_method('(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;J)V') def onDownloadStart(self, url, userAgent, contentDisposition, mimetype, contentLength): mActivity = PythonActivity.mActivity context = mActivity.getApplicationContext() visibility = DownloadManagerRequest.VISIBILITY_VISIBLE_NOTIFY_COMPLETED dir_type = Environment.DIRECTORY_DOWNLOADS uri = Uri.parse(url) filepath = uri.getLastPathSegment() request = DownloadManagerRequest(uri) request.setNotificationVisibility(visibility) request.setDestinationInExternalFilesDir(context, dir_type, filepath) dm = cast(DownloadManager, mActivity.getSystemService(Context.DOWNLOAD_SERVICE)) dm.enqueue(request)

class CustomWebChromeClient(WebChromeClient):
javaclass = 'android/webkit/WebChromeClient'
metaclass = MetaJavaClass
def onShowFileChooser(self, webView, filePathCallback, fileChooserParams):
# Handle file chooser request here

intent = Intent(Intent.ACTION_GET_CONTENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.setType("*/*") chooserIntent = Intent.createChooser(intent, "Choose a file") PythonActivity.mActivity.startActivityForResult(chooserIntent, 1) # Save the callback for handling the selected file self.filePathCallback = filePathCallback return True def onActivityResult(self, requestCode, resultCode, intent): if requestCode == 1: if resultCode == -1: # RESULT_OK # Get the selected file's URI and pass it to the WebView selected_file_uri = intent.getData() self.filePathCallback.onReceiveValue(selected_file_uri) else: # Handle the case where file selection was canceled by the user self.filePathCallback.onReceiveValue(None)

class KeyListener(PythonJavaClass):
javacontext = 'app'
javainterfaces = ['android/view/View$OnKeyListener']

def __init__(self, listener): super().__init__() self.listener = listener @java_method('(Landroid/view/View;ILandroid/view/KeyEvent;)Z') def onKey(self, v, key_code, event): if event.getAction() == KeyEvent.ACTION_DOWN and key_code == KeyEvent.KEYCODE_BACK: return self.listener() # Убрвть самодеятельность return super(KeyListener, self).onKey(v, key_code, event)

class ImageButtonClickListener(PythonJavaClass):
javainterfaces = ['android/view/View$OnClickListener']
def init(self, listener):
super().init()
self.listener = listener

@java_method('(Landroid/view/View;)V') def onClick(self, view): try: return self.listener() except Exception as e: print("error", e)

class WebView(ModalView):
# https://developer.android.com/reference/android/webkit/WebView

def __init__(self, screen_manager, url="", enable_raw_html=False, html="", enable_javascript=False, enable_downloads=False, enable_zoom=False, **kwargs): super().__init__(**kwargs) self.url = url self.screen_manager = screen_manager self.enable_raw_html = enable_raw_html self.html = html self.enable_javascript = enable_javascript self.enable_downloads = enable_downloads self.enable_zoom = enable_zoom self.webview = None self.layout = None self.enable_dismiss = True self.headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/111.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'br', 'Authorization': f'Bearer {self.screen_manager.model.token}', 'Content-Type': 'application/json' } self.open() def but_click_func(self, instance): self._back_pressed() @run_on_ui_thread def on_open(self): mActivity = PythonActivity.mActivity webview = WebViewA(mActivity) custom_webchromeclient = CustomWebChromeClient() webview.setWebChromeClient(custom_webchromeclient) webview.setWebViewClient(WebViewClient()) webview.getSettings().setLoadsImagesAutomatically(True) webview.getSettings().setJavaScriptEnabled(self.enable_javascript) webview.getSettings().setBuiltInZoomControls(self.enable_zoom) webview.getSettings().setDisplayZoomControls(False) webview.getSettings().setAllowFileAccess(True) # default False api>29 webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW) webview.getSettings().setDomStorageEnabled(True) webview.setWebContentsDebuggingEnabled(True) layout = LinearLayout(mActivity) layout.setOrientation(LinearLayout.VERTICAL) layout.setBackgroundColor(Color.parseColor("#673ab7")) iner_layout = LinearLayout(mActivity) iner_layout.setOrientation(LinearLayout.VERTICAL) iner_layout.setBackgroundColor(Color.parseColor("#673ab7")) iner_layout.setPadding(75, 0, 0, 0) layout.addView(iner_layout, self.width, 60) # Add back button back_button = Button(mActivity) back_button.setImageResource(mActivity.getResources().getIdentifier('arrow_left_custom', 'drawable', mActivity.getPackageName())) back_button.setBackgroundColor(0x00000000) # Set background to transparent back_button.setPadding(0, 0, 0, 0) # Remove padding back_button.setElevation(0) # Remove shadow back_button.setBackground(None) # Remove default background back_button.setOnClickListener(ImageButtonClickListener(self._back_pressed)) iner_layout.addView(back_button, 50, 50) layout.addView(webview, self.width, self.height-60) mActivity.addContentView(layout, LayoutParams(-1, -1)) webview.setOnKeyListener(KeyListener(self._back_pressed)) self.webview = webview self.layout = layout if self.enable_downloads: webview.setDownloadListener(DownloadListener()) if self.enable_raw_html: try: webview.loadDataWithBaseURL("", self.html, "text/html", "utf-8", "") except Exception as e: print('Webview.on_open(): ' + str(e)) self.dismiss() else: try: headers_map = HashMap() for key, value in self.headers.items(): headers_map.put(String(key), String(value)) self.webview.loadUrl(self.url, headers_map) except Exception as e: print('Webview.on_open(): ' + str(e)) @run_on_ui_thread def on_dismiss(self): if self.enable_dismiss: self.enable_dismiss = False parent = cast(ViewGroup, self.layout.getParent()) if parent is not None: parent.removeView(self.layout) self.webview.clearHistory() self.webview.clearCache(True) self.webview.clearFormData() self.webview.destroy() self.layout = None self.webview = None @run_on_ui_thread def on_size(self, instance, size): if self.webview: params = self.webview.getLayoutParams() params.width = self.width params.height = self.height self.webview.setLayoutParams(params) def pause(self): if self.webview: self.webview.pauseTimers() self.webview.onPause() def resume(self): if self.webview: self.webview.onResume() self.webview.resumeTimers() def downloads_directory(self): # e.g. Android/data/org.test.myapp/files/Download dir_type = Environment.DIRECTORY_DOWNLOADS context = PythonActivity.mActivity.getApplicationContext() directory = context.getExternalFilesDir(dir_type) return str(directory.getPath()) def _back_pressed(self): if self.webview.canGoBack(): self.webview.goBack() else: self.dismiss() return True

`

--
You received this message because you are subscribed to the Google Groups "Kivy development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-dev+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-dev/f28e0ae2-1169-4ea0-9f5a-14acc031e113n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages