Menus

Saturday 4 March 2017

Set icon for android application


How can I set an icon for my android application?

Solutions for using set icon my android studio project

Steps

1 Choose icon picture copy this pic
2 Paste it into your project's res/drawable folder
3 Open manifest file and set 
    <application
   android:allowBackup="true"
   android:icon="@drawable/calendar"
   android:label="@string/app_name"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
.....
</application>
4 Run program








Show menu items in action bar




Friday 3 March 2017

Show menu items in action bar


Menu items are showing on action BAR




Android action bar was used to maintain a consistent navigation across the application. Menu list button show on action bar.

Screen shot



Android - Navigation




Overview of Action Bar

Action bar mainly contains four functional areas. They are app icon, view control, action buttons and action overflow.
App Icon – App branding logo or icon will be displayed here.
View Control – A dedicated space to display app title. Also provides option to switch between views by adding spinner or tabbed navigation.
Action Buttons – Some important actions of the app can be added here.
Action Overflow – All unimportant action will be shown as a menu.

Here the important xml attributes should be known are
android:icon – Defines the icon of the action item.
android:title – Title for the icon.
android:showAsAction – Defines the visibility of the action item. It accepts following values.
ifRoomDisplays the icon if there is space available on the screen
neverNever places this icon on the action bar
alwaysForces to display the icon always irrespective of space available. This way is not suggested.
withTextDisplays a text along with the icon. Normally the text value defined by android:title will be displayed
collapseActionViewDefines the action layout associated with it. This action view defined usingandroid:actionLayout or android:actionViewClass



Example

Add menu title set as res/values/strings.xml


<resources>

    ....
    <string name="entries">ENTRIES</string>
    <string name="entrieslist">ENTRIES LIST</string>
    <string name="salesreport">SALES REPORT</string>
    <string name="logout">LOGOUT</string>


</resources>




Create a new xml file under res ⇒ menu named main_actions.xml and add the following code. 
Here each <item> indicates each action item.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/entries"
        android:title="@string/entries"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/entrieslist"
        android:title="@string/entrieslist"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/salesreport"
        android:title="@string/salesreport"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/logout"
        android:title="@string/logout"
        app:showAsAction="never"
        />
</menu>


Now open your main activity class and do the following in onCreateOptionsMenu() method.


public class RptsalesreportActivity extends AppCompatActivity {


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

         ...............
    } 


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_actions, menu);

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

         switch (item.getItemId()) {
        case R.id.entries:
            // code here
            return true;
        case R.id.entrieslist:
            //code here
            return true;
        case R.id.salesreport:
            //code here
            return true;
        case R.id.logout:
            //code here
            return true;      
        default:
            return super.onOptionsItemSelected(item);
        }
        
    }


}


Handling Action Bar Icon Click Events

Open your main activity and override onOptionsItemSelected() method. This method accepts menu item as a parameter. Selected action item can be identified by using it’s id. 





Thursday 2 March 2017

Android Long Press Event



Android Long Press Event



There are many situation in which your application needs to long press event.

  (viewitem).setOnLongClickListener(new OnItemLongClickListener() {           
        @Override
        public boolean onLongClick(View v) {
            //your code here
            return false;
        }
    }

Long Press Button Event Handler


Button button = (Button) findViewById(R.id.btn_NextLift);

button.setOnLongClickListener(new OnLongClickListener() { 
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return true;
        }
    });

Example of android long press event operation






XML file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.root.calendar.MainActivity"
    tools:showIn="@layout/activity_main"
    >


    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        tools:context=".LongPress"
        android:layout_height="40dp"
        android:layout_alignEnd="@+id/calendarView">

        <TextView
            android:id="@+id/txtView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="" />

    </RelativeLayout>


    <com.prolificinteractive.materialcalendarview.MaterialCalendarView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        app:mcv_showOtherDates="all"
        app:mcv_selectionColor="#00F"
        />

</RelativeLayout>



Java File


package com.example.root.calendar;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

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


        TextView txtView = (TextView) findViewById(R.id.txtView);
        txtView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                return true;
            }
        });


    }
}






Related Links

Event Handling in Android

Transfer Data Between Activities Using Intent
Android Programming Tips



Tuesday 28 February 2017

Transfer Data Between Activities Using Intent



user interface is displayed through an activity(Screen). Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and they can interact with each other


Interaction between multiple activities can be done only using Intent. Intents are objects of theandroid.content.Intent type. Your code can send them to the Android system defining the components you are targeting. In Android app development you face situations where you want to send or receive your data between one Activity (Screen) to another. 


Calling one Activity from another in Android


Define an intent that will be sent to Activity2:
Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);

Current activity Activity1 and the one you wish to open - Activity2.


Sample

Intent intent = new Intent(HomeActivity.this, EntriesActivity.class);
startActivity(intent);



Button entriesButton = (Button)findViewById(R.id.btnEntries);
entriesButton.setOnClickListener(new View.OnClickListener() {

    @Override    public void onClick(View v) {

        Intent intent = new Intent(HomeActivity.this, EntriesActivity.class);
        startActivity(intent);
    }
});



pass data between activities on Android

In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);

i.putExtra("key","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
Sample
Current activity
btnGenerate=(Button)findViewById(R.id.btnGenerate);
btnGenerate.setOnClickListener(new View.OnClickListener(){
    @Override    public void onClick(View view) {

        Intent myIntent = new Intent(RptsalesreportActivity.this, RptsalesreportdisplayActivity.class);
        myIntent.putExtra("day", "12");
        myIntent.putExtra("month", "2");
        myIntent.putExtra("year", "2017");
        startActivity(myIntent);

    }

});
New activity
Intent intent = getIntent();
String day = intent.getStringExtra("day");
String month = intent.getStringExtra("month");
String year = intent.getStringExtra("year");
value access by using getIntent() method.



Android Call An Activity class from a java class

Pass string value and Current Activity Context to function menuActions in Genfunctions class.
Java class like this
package com.example.root.calendar;

import android.content.Context;
import android.content.Intent;

public class Genfunctions {



    public void menuActions(String title,Context ct){

        //this.context=context;
        switch (title){
            case "ENTRIES":

                Intent intent = new Intent(ct, RptentrylistActivity.class);
                ct.startActivity(intent);
                break;
        }

    }//end of functions

}
Activity Class function call like this
Genfunctions gn = new Genfunctions(); gn.menuActions("ENTRIES",this);

Sunday 19 February 2017

Android - SQLite Tips




Android sqlite check if inserted new value


insert() method returns the row ID of the newly inserted row, or -1 if an error occurred.
Like this:
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
    Toast.makeText(myContext, "New row added, row id: " + rowInserted, Toast.LENGTH_SHORT).show();
else
    Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();

Called from main activity for save item record to SQLite table and return status true or false.

public boolean insertItem(HashMap<String, String> queryValues) {

    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();


    values.put("edate",queryValues.get("edate"));
    values.put("item",queryValues.get("item"));
    values.put("amount",queryValues.get("amount"));
    values.put("number",queryValues.get("number"));
    values.put("count",queryValues.get("count"));

        long rowInserted = database.insert("customerentries", null, values);

        if(rowInserted != -1) {
            database.close();
            return true;
        }
        else{
            database.close();
            return false;
        }

}


Click Here




Android SQLite find for max value in a field


How to get the Max value SQLite Android



The SQLite MAX function is an aggregate function that returns the maximum value of all values in a group. 


    public int getMaxid(){

        String selectQuery = "SELECT max(id) as id FROM customerentries";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);

        cursor.moveToFirst();

        int maxid = cursor.getInt(cursor.getColumnIndex("id"));

        return maxid;
       
    }

Solution for - 

How to find the maximum value of the column in sqlite database



Related Links




Wednesday 8 February 2017

Add a row to the table


Adding Table rows Dynamically in Android

Display Data in GridView in Android

How to use TextView to display GridView item text in Android ?


Output Form like this





Solutions:

Layout file like:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.mymysqlapp.Table2Activity">


<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >

<HorizontalScrollView
    android:id="@+id/hscrll1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TableLayout
            android:id="@+id/table_main"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true" >
        </TableLayout>
    </RelativeLayout>
</HorizontalScrollView>
</ScrollView>


</RelativeLayout>


Code like this :

Create an init() function and point the table layout. Then create the needed rows and columns. Call init function in your onCreate method:



package com.example.root.mymysqlapp;



import android.graphics.Color;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Gravity;

import android.widget.TableLayout;

import android.widget.TableRow;

import android.widget.TextView;

public class Table2Activity extends AppCompatActivity {

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


        init();

    }


    public void init() {

        TableLayout stk = (TableLayout) findViewById(R.id.table_main);
        TableRow tbrow0 = new TableRow(this);

        TextView tv0 = new TextView(this);
        tv0.setText(" Sl.No ");
        tv0.setTextColor(Color.WHITE);
        tbrow0.addView(tv0);

        TextView tv1 = new TextView(this);
        tv1.setText(" Student Name ");
        tv1.setTextColor(Color.WHITE);
        tbrow0.addView(tv1);

        TextView tv2 = new TextView(this);
        tv2.setText(" Class ");
        tv2.setTextColor(Color.WHITE);
        tbrow0.addView(tv2);

        TextView tv3 = new TextView(this);
        tv3.setText(" Total Fee ");
        tv3.setTextColor(Color.WHITE);
        tbrow0.addView(tv3);

        stk.addView(tbrow0);

        for (int i = 1; i <= 25; i++) {
            TableRow tbrow = new TableRow(this);

            TextView t1v = new TextView(this);
            t1v.setText(""+i);
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            tbrow.addView(t1v);

            TextView t2v = new TextView(this);
            t2v.setText("Student " + i);
            t2v.setTextColor(Color.WHITE);
            t2v.setGravity(Gravity.CENTER);
            tbrow.addView(t2v);

            TextView t3v = new TextView(this);
            t3v.setText("1-A");
            t3v.setTextColor(Color.WHITE);
            t3v.setGravity(Gravity.CENTER);
            tbrow.addView(t3v);

            TextView t4v = new TextView(this);
            t4v.setText("1500.00");
            t4v.setTextColor(Color.WHITE);
            t4v.setGravity(Gravity.CENTER);
            tbrow.addView(t4v);

            stk.addView(tbrow);
        }

    }

}

Above application expline working of TableLayout .





How add and delete rows to table layout in java programically


How to delete table row in table layout in android


Layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/table"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

</TableLayout>
Activity:
public class TableLayoutActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.table_layout);
    final TableLayout tableLayout = (TableLayout) findViewById(R.id.table);

    for (int i = 0; i < 5; i++) {
        // Creation row
        final TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));

        // Creation textView
        final TextView text = new TextView(this);
        text.setText("Test" + i);
        text.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));

        // Creation  button
        final Button button = new Button(this);
        button.setText("Delete");
        button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final TableRow parent = (TableRow) v.getParent();
                tableLayout.removeView(parent);
            }
        });

        tableRow.addView(text);
        tableRow.addView(button);

        tableLayout.addView(tableRow);
    }

}
}


Inserting table row beginning of table layout in java programmatically


tbl.addView(View child, int index)

child contains rows object and index contains for add row position in table layout.

Example

tbl.addView(row,0);  // added first row
tbl.addView(row,1);  // added second row
.
.
tbl.addView(row);  // added row in end of table layout.



Dynamically add imagebutton programatically android


ImageButton b1 = new ImageButton(this);
b1.setImageResource(R.drawable.delete);
b1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
b1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final TableRow parent = (TableRow) v.getParent();
        stk.removeView(parent);
    }
});

tbrow.addView(b1);




How do I get values from a dynamically created android TableRow?



getChildAt to get a hold of the two TextViews and get the data:

tr.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
      TableRow t = (TableRow) view;
      TextView firstTextView = (TextView) t.getChildAt(0);
      TextView secondTextView = (TextView) t.getChildAt(1);
      String firstText = firstTextView.getText().toString();
      String secondText = secondTextView.getText().toString();
   }
});


Solution for the get values of selected row on clicked button in table row.


ImageButton b1 = new ImageButton(EntriesActivity.this);
b1.setImageResource(R.drawable.delete);
b1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
b1.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        final TableRow parent = (TableRow) v.getParent();

        //code for remove concerned row
        //stk.removeView(parent);
        TextView items = (TextView) parent.getChildAt(7);

        Toast.makeText(getApplicationContext(), items.getText().toString() ,Toast.LENGTH_SHORT).show();


    }
});
row.addView(b1);



How to hide a particular column in Android TableRow



Try to Use setVisibility(View.GONE); 
t3v.setVisibility(View.GONE);

TextView id = new TextView(EntriesActivity.this);
id.setText(content.get("id").toString());
id.setTextColor(Color.WHITE);
id.setVisibility(View.GONE);
row.addView(id);




Get total RowCount for TableLayout in Android



Through this code you can get the total rowCount for TableLayout
TableLayoutName.getChildCount();

Examples

TableLayout tb = (TableLayout) findViewById(R.id.table_main);

if(tb.getChildCount()>1){

.....Code Here.....

}



Adding space between columns of a TableLayout


 Programetically  add

  TextView count = new TextView(RptsalesreportdisplayActivity.this);
  count.setText(obj.get("count").toString());
  count.setTextColor(Color.WHITE);
  count.setPadding(0,0,30,0);
  row.addView(count);


<TableRow
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="0"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:gravity="center"
        android:text="col1" />   ...........


Set tablelayout row background color programmatically


tbrow0.setBackgroundResource(R.color.cgreen);