How to run Python code in Android App?

Programmer World
Programmer World
324 بار بازدید - 2 ماه پیش - In this video it shows
In this video it shows the steps to run a python code in Android App's code. It calls the python script from the Java code. It uses chaquo plugin, which is Python SDK for Android. Details are available at: https://chaquo.com/chaquopy/

The steps for setting the Gradle is taken from this page: https://chaquo.com/chaquopy/doc/curre...


I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...


However, the main Java code is copied below also for reference:


package com.programmerworld.pythininandroidapp;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

public class MainActivity extends AppCompatActivity {

   private TextView textViewOutput;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       EdgeToEdge.enable(this);
       setContentView(R.layout.activity_main);
       ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) - {
           Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
           v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);

           textViewOutput = findViewById(R.id.textViewOutput);
           Python.start(new AndroidPlatform(getApplicationContext()));

           return insets;
       });
   }

   public void buttonPythonRun(View view){
       Python python = Python.getInstance();
       PyObject pyObjectResult = python.getModule("add_numbers")
               .callAttr("add_numbers", 10, 25);
       textViewOutput.setText(pyObjectResult.toString());
   }
}


--
2 ماه پیش در تاریخ 1403/03/08 منتشر شده است.
324 بـار بازدید شده
... بیشتر