Wednesday 2 August 2017

Change Fragment on button click in Android

In example mention below on click of a button, we attach the desired fragment in our frame layout which was present in activity_main.xml.




Step 1: -Open your project and design layout of your app in activity-main.xml.

activity_main.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:id="@+id/number_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.hp.myframepart2.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/fragment_one"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/fragment_one"
        android:onClick="sendframe"/>
    <Button
        android:id="@+id/fragment_two"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="@string/fragment_two"
        android:onClick="sendframe"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <FrameLayout
        android:id="@+id/color_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

    </LinearLayout>
</LinearLayout>


Step 2: -Create a new xml which act as the fragment which attaches to our frame layout.

fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fragment_field"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="@dimen/textsize"
        android:padding="@dimen/textpadding"
        android:gravity="center"
        android:textColor="@android:color/white"/>

</LinearLayout>

string.xml
<resources>
    <string name="app_name">MyFramepart2</string>
    <string name="fragment_one">FRAGMENT ONE</string>
    <string name="fragment_two">FRAGMENT TWO</string>
</resources>


Step 3: -Create another java class to attach our fragment to frame layout.

TextFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TextFragment extends Fragment {
    private View view;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_one,container,false);
        return  view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Bundle bundle=getArguments();
        if(bundle!=null){
            String data=bundle.getString(MainActivity.TEXT);
            int color=bundle.getInt(MainActivity.COLOR);
            TextView textView=(TextView)view.findViewById(R.id.fragment_field);
            textView.setText(data);
            textView.setBackgroundColor(color);
        }
    }
}


Step 4: - To give text size or dimension we give it dynamically in dimen.xml.In it, we mention size or dimension and call it dynamically in a project. To create dimen.xml go to res→values(right click)→Values resource file then press ok.Inside dimen.xml you mention your dimension related requirement.

dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <dimen name="textsize">25sp</dimen>
   <dimen name="textpadding">16dp</dimen>
</resources>


Step 5: -Open your MainActivity.java class and type the code mention below to perform the operation.

MainActivity.java
package com.example.hp.myframepart2;

import android.graphics.Color;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public final static String TEXT = "org.mz.Activity.text";
    public final static String COLOR = "org.mz.Activity.color";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void sendframe(View view) {
        TextFragment changeFragmentOnClick = new TextFragment();
        Button button = (Button) view;
        Bundle bundle = new Bundle();
        String buttonText = button.getText().toString();
        if (buttonText.equals("FRAGMENT ONE")) {
            bundle.putInt(COLOR, (Color.RED));
        } else {
            bundle.putInt(COLOR, (Color.BLUE));
        }

        bundle.putString(TEXT, buttonText);
        changeFragmentOnClick.setArguments(bundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.color_fragment, changeFragmentOnClick);
        transaction.commit();
    }
}


   

Save File in External Storage in Android


There are two categories of files we might save in External Storage.

1.) Public files→Files that are freely available to other app and user.When the user uninstalls app these files should remain available to the user.
2.) Private files→Files that rightfully belong to the app and should be deleted when user uninstall your app.

To save the public file in external storage we need a method getExternalStoragePublicDirectory() method.e file
To save the private file in external storage we need method getExternalFilesDir().
Here we are dealing with external storage.To work with external storage we need permission.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

This permission is required to read or write date from external storage.This permission is placed in AndroidManifest.xml.I give you the example as mention below.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hp.publicfileexternalstorage">
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




Step 1: -Write code in activity_main.xml to design your layout.                                                      

activity_main.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"
    android:orientation="vertical"
    tools:context="com.example.hp.publicfileexternalstorage.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/entername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SAVE"
            android:onClick="savedata"/>
        <Button

            android:id="@+id/retreive"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="RETRIEVE"
            android:onClick="retreivdata"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="15sp"/>
    </LinearLayout>


</LinearLayout>


Step 2: -Type code in MainActivity.xml to save the file in External storage.

MainActivity.xml
package com.example.hp.publicfileexternalstorage;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG=MainActivity.class.getSimpleName();
    TextView display;
    File file;
    File file1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(LOG_TAG,"create");
        display=(TextView)findViewById(R.id.display);
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "file"); //To save public file in external storage;
        file = new File(getExternalFilesDir("MyDocument"), "appfile.txt"); //To save private file in external storage;      
 if (!file.mkdir()) {
            Log.e(LOG_TAG,"Directory not created");
        }else{
            Log.e(LOG_TAG,"Directory created");
        }

    }
    public void savedata(View view){
         file1=new File(file,"Mytext.txt");
        EditText name=(EditText)findViewById(R.id.entername);
        String username=name.getText().toString();
        try {
            FileOutputStream outputStream=new FileOutputStream(file1);
            outputStream.write(username.getBytes());
            outputStream.close();
            name.setText("");

        }
        catch (FileNotFoundException e){
            e.printStackTrace();

        }

        catch (IOException e){
            e.printStackTrace();
        }

    }
    public void retreivdata(View view) {
        try {
            FileInputStream inputStream = new FileInputStream(file1);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp, temp1 = "";
                try {
                    while ((temp = bufferedReader.readLine()) != null)
                        temp1 += temp;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                display.setText(temp1);
                inputStream.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }


    }



}





Tuesday 1 August 2017

Save File in Internal Storage in Android


In Android, we have to way to store data.

1.) Internal storage
2.) External storage

In the below example we use internal storage to store data and retrieve date from the same location.I am using internal storage so we don't need for permission to access internal storage.But when we use external storage we need permission to read or write on external storage.In this example on click of save button value of edit-text saved in internal storage and value retrieve on click of a retreive button.






Step 1: -Open your project and in activity_main.xml create the design of your own requirement.To give you the idea I am creation simple design.      

activity_main.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"
    android:orientation="vertical"
    tools:context="com.example.hp.mysavefile.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <EditText
        android:id="@+id/entername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="SAVE"
        android:onClick="savedata"/>
        <Button

            android:id="@+id/retreive"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="RETRIEVE"
            android:onClick="retreivdata"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="15sp"/>
    </LinearLayout>

</LinearLayout>


Step 2: -Open your MainActivity.java and write code MainActivity.java I am writing code for save button and retrieve button.

MainActivity.java
package com.example.hp.mysavefile;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
 TextView display;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        display=(TextView)findViewById(R.id.display);

    }
                public void savedata(View view){
                EditText name=(EditText)findViewById(R.id.entername);
                String username=name.getText().toString();
                try {
                    FileOutputStream outputStream=openFileOutput("amit.txt", Context.MODE_PRIVATE);
                    outputStream.write(username.getBytes());
                    outputStream.close();

                    name.setText("");
                }
                catch (FileNotFoundException e){
                    e.printStackTrace();

                }

                catch (IOException e){
                    e.printStackTrace();
                }
            }
            public void retreivdata(View view) {
                try {
                    FileInputStream inputStream = openFileInput("amit.txt");
                    if (inputStream != null) {
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        String temp, temp1 = "";
                        try {
                            while ((temp = bufferedReader.readLine()) != null)
                                temp1 += temp;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        display.setText(temp1);
                        inputStream.close();
                    }
                }
            catch (Exception e) {
            e.printStackTrace();
            }


                        }
                    }








                                                                 


Custom Listview in Android


  Listview: -

It is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter pulls content from a source such as an array or database query and converts each item result into a view that's placed on the list.

 

Step 1: - Open your project.In your activity.xml creates list view as mention below.                          
         
activity_main.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="com.example.hp.mylistview.MainActivity">
   <ListView
       android:id="@+id/product_list"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       />
</LinearLayout>

          
Step 2: -Now create another xml which attach to our list view.

row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
      <TextView
          android:id="@+id/product_name"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />
      <TextView
          android:id="@+id/product_price"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />
</LinearLayout>

In it, I am using two text-view to show two texts in our list view.

Step 3: -Now create a bean class to describe our component.

Product.java

public class Product {
    private String productName;
    private String productPrice;
    public Product(String productName,String productPrice){
        this.productName=productName;
        this.productPrice=productPrice;
    }

    public String getProductName() {
        return productName;
    }

    public String getProductPrice() {
        return productPrice;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public void setProductPrice(String productPrice) {
        this.productPrice = productPrice;
    }
}

Step 4: - I am creating custom Listview.In it I am using two text view for that we need to create an adapter class.If I need to display only one text in one row then we do not need to create custom adapter there is default adapter that we use.

ListAdapter.java

public class ListAdapter extends ArrayAdapter<Product>{
    private Context context;
    private List<Product> productList;
    private int id;
    public ListAdapter(Context context,int id,List<Product> productList){
        super(context,id,productList);
        this.context=context;
        this.id=id;
        this.productList=productList;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView==null){
            LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView=inflater.inflate(id,parent,false);
        }
        TextView productName=(TextView) convertView.findViewById(R.id.product_name);
        TextView productPrice=(TextView) convertView.findViewById(R.id.product_price);
        productName.setText(productList.get(position).getProductName());
        productPrice.setText(productList.get(position).getProductPrice());
        return  convertView;
    }
}

Step 5: -Now time to write code in MainActivity.java.

MainActivity.java
package com.example.hp.mylistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<Product> productList=new ArrayList<>();
        productList.add(new Product("Kurkure","10"));
        productList.add(new Product("Kurkure","20"));
        productList.add(new Product("Kurkure","30"));
        productList.add(new Product("Kurkure","40"));
        productList.add(new Product("Kurkure","50"));
        productList.add(new Product("Kurkure","60"));
        productList.add(new Product("Kurkure","70"));
        ListView listView=(ListView)findViewById(R.id.product_list);
        ListAdapter adapter=new com.example.hp.mylistview.ListAdapter(this,R.layout.row,productList);
        listView.setAdapter(adapter);



    }
}


Change Fragment on button click in Android

In example mention below on click of a button, we attach the desired fragment in our frame layout which was present in activity_main.xml. ...