• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Do I create a dynamic layout xml using android studio?

jackraj25

Lurker
May 8, 2018
3
0
Aim
For example, I want to select a few fields from the list of fields of a Web page[MVC ASP.NET] and design a separate section[Student screen, Teacher screen, Mark screen ] using the android studio.
While login to an app via WCF restful web services,
I need to get those fields and each text values should be saved to the local SQLite database when saving the values and automatically sync values.

MVC ASP.NET
WCF RESTFUL SERVICES
ANDROID STUDIO

I the following link

https://www.javacodegeeks.com/2012/09/android-dynamic-and-xml-layout.html

https://medium.com/@uddishverma22/creating-dynamic-layouts-in-android-d4008b72f2d
 
Code:
package com.example.rajkumar.dynamicapplication;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class MainActivity extends AppCompatActivity {

    private String filename = "SampleFile.txt";
    private String filepath = "MyFileStorage";
    File myExternalFile;
    String myData = "";
    EditText et;
    EditText etAge;

    //http://www.androhub.com/android-creating-layouts-programatically/
    //https://medium.com/@uddishverma22/creating-dynamic-layouts-in-android-d4008b72f2d
    //https://www.javacodegeeks.com/2012/09/android-dynamic-and-xml-layout.html
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // This will create the LinearLayout
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        // Configuring the width and height of the linear layout.
        LayoutParams llLP = new LayoutParams(
                //android:layout_width='match_parent' an in xml
                LinearLayout.LayoutParams.MATCH_PARENT,
                //android:layout_height='wrap_content'
                LinearLayout.LayoutParams.MATCH_PARENT);
        ll.setLayoutParams(llLP);

        TextView tv = new TextView(this);
        LayoutParams lp = new LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        ///Textview started
        tv.setLayoutParams(lp);
        //android:text='@string/name'
        tv.setText(R.string.name);
        //android:padding='@dimen/padding_medium'
        tv.setPadding(8, 8, 8, 8);
        ll.addView(tv);
        ///Edittext
        et = new EditText(this);
        et.setLayoutParams(lp);
        et.setHint(R.string.entername);
        et.setPadding(8, 8, 8, 8);
        ll.addView(et);

        //Age
        TextView tage = new TextView(this);
        tage.setLayoutParams(lp);
        //android:text='@string/name'
        tage.setText(R.string.Age);
        //android:padding='@dimen/padding_medium'
        tage.setPadding(8, 8, 8, 8);
        ll.addView(tage);

        ///Edittext Age
        etAge = new EditText(this);
        etAge.setLayoutParams(lp);
        etAge.setHint(R.string.enterage);
        etAge.setPadding(8, 8, 8, 8);
        ll.addView(etAge);

        //Gender
        TextView tgender = new TextView(this);
        tgender.setLayoutParams(lp);
        //android:text='@string/name'
        tgender.setText(R.string.Gender);
        //android:padding='@dimen/padding_medium'
        tgender.setPadding(8, 8, 8, 8);
        ll.addView(tgender);

        //RadioButtons are always added inside a RadioGroup
        RadioGroup radioGroup = new RadioGroup(this);
        radioGroup.setOrientation(LinearLayout.HORIZONTAL);
        //ll.addView(radioGroup);
        //Male radiobutton
        RadioButton radioButton = new RadioButton(this);
        radioButton.setText(R.string.Male);
        radioGroup.addView(radioButton);
        //Female radiobutton
        RadioButton femaleradioButton = new RadioButton(this);
        femaleradioButton.setText(R.string.Female);
        radioGroup.addView(femaleradioButton);
        ll.addView(radioGroup);

        //Year
        TextView tyear = new TextView(this);
        tyear.setLayoutParams(lp);
        //android:text='@string/name'
        tyear.setText(R.string.Year);
        //android:padding='@dimen/padding_medium'
        tyear.setPadding(8, 8, 8, 8);
        ll.addView(tyear);

        //Spinner
        ArrayList<String> years = new ArrayList<String>();
        int thisYear = Calendar.getInstance().get(Calendar.YEAR);
        for (int i = 1900; i <= thisYear; i++) {
            years.add(Integer.toString(i));
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);
        Spinner spinner=new Spinner(this);
        spinner.setAdapter(adapter);
        spinner.setLayoutParams(lp);
        ll.addView(spinner);

        ////Button
        Button bt = new Button(this);
        bt.setText(R.string.OtherActivity);
        bt.setPadding(8, 8, 8, 8);
        ll.addView(bt);

        ////Button
        Button read = new Button(this);
        read.setText(R.string.Read);
        read.setPadding(8, 8, 8, 8);
        ll.addView(read);

        //Now finally attach the Linear layout to the current Activity.
        setContentView(ll);

        //Attach OnClickListener to the button.
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),"This is dynamic activity", Toast.LENGTH_LONG).show();
                //Intent intent=new Intent(MainActivity.this,activity_androidxml.class);
                //startActivity(intent);
                try {
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                    fos.write(et.getText().toString().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                et.setText("");
            }
        });

        read.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileInputStream fis = new FileInputStream(myExternalFile);
                    DataInputStream in = new DataInputStream(fis);
                    BufferedReader br =
                            new BufferedReader(new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                        myData = myData + strLine;
                    }
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                etAge.setText(myData);
                //response.setText("SampleFile.txt data retrieved from External Storage...");
            }

        });

        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            bt.setEnabled(false);
        }
        else {

            String xmlpath=GetFilePath();
            Document file= convertStringToDocument(xmlpath);

        }


    }
    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }
    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }
    private String GetFilePath(){
        String databasepath=null;
        myExternalFile = new File(getExternalFilesDir(filepath), filename);
        if(!myExternalFile.exists()) {


            try {
                //now create xml
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                // create root: <record>
                Element root = doc.createElement("Root");
                doc.appendChild(root);

                // create Transformer object
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                transformer.transform(new DOMSource(doc), result);

                //TransformerFactory tfact = TransformerFactory.newInstance();
                //Transformer tform = tfact.newTransformer();
                //tform.setOutputProperty(OutputKeys.INDENT, "yes");

            } catch (ParserConfigurationException e) {

            }
            catch (TransformerException e) {

            }

        }
        databasepath=myExternalFile.getPath();
        return  databasepath;
    }
    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try
        {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) );
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
Upvote 0
I'm not understanding why you can't create all these UI components in an XML layout file. If you know all the components you need at compile time, there's no requirement for this dynamic approach.

The values are obtained from a remote web service, but the actual UI components (e.g. TextView) can be specified in XML.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones