battle programminga forum for elite programmerswith extreme will powerto sharpen theire skills
 
HomeCalendarFAQSearchMemberlistUsergroupsRegisterLog in
Share | 
 

 android mobile app dev APK

Go down 
Go to page : Previous  1, 2, 3  Next
AuthorMessage
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android : moving the location of an Image View using java code   Mon Jun 18, 2018 10:52 am

imageView1.setY(imageView1.getY() + 200);

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android SQlite walkthrough   Wed Jun 20, 2018 7:00 pm




The database created is saved in a directory: data/data/APP_Name/databases/DATABASE_NAME.

data table : (String name, String pass) this are to example fields
you can see them in the inner class : myDbHelper in myDbAdapter class
replace and add fields on them to customize your SQDB


main xml :


Code:
<?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"
    tools:context=".MainActivity">

    <TextView
        android:text="username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="12dp"
        android:id="@+id/textView"
        android:textSize="18sp"
        android:textStyle="bold|italic"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:gravity="center" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editName"
        android:textStyle="bold|italic"
        android:layout_below="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Enter Name"
        android:gravity="center_vertical|center" />

    <TextView
        android:text="password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="13dp"
        android:id="@+id/textView2"
        android:textStyle="bold|italic"
        android:textSize="18sp"
        android:layout_below="@+id/editName"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:gravity="center"
        android:hint="Enter Password" />

    <Button
        android:text="view_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:textSize="18sp"
        android:onClick="viewdata"
        android:textStyle="bold|italic"
        android:layout_alignBaseline="@+id/button"
        android:layout_alignBottom="@+id/button"
        android:layout_alignRight="@+id/button4"
        android:layout_alignEnd="@+id/button4" />

    <Button
        android:text="add_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:textStyle="bold|italic"
        android:textSize="18sp"
        android:onClick="addUser"
        android:layout_marginLeft="28dp"
        android:layout_marginStart="28dp"
        android:layout_below="@+id/editPass"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="23dp" />

    <Button
        android:text="update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        android:onClick="update"
        android:textStyle="normal|bold"
        android:layout_below="@+id/editText3"
        android:layout_alignLeft="@+id/button4"
        android:layout_alignStart="@+id/button4"
        android:layout_marginTop="13dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText6"
        android:layout_alignTop="@+id/button4"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:freezesText="false"
        android:hint="Enter Name to Delete Data"
        android:layout_toLeftOf="@+id/button2"
        android:layout_toStartOf="@+id/button2" />

    <Button
        android:text="delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="21dp"
        android:layout_marginEnd="21dp"
        android:id="@+id/button4"
        android:onClick="delete"
        android:textStyle="normal|bold"
        tools:ignore="RelativeOverlap"
        android:layout_marginBottom="41dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_marginTop="47dp"
        android:id="@+id/editText3"
        android:textStyle="bold|italic"
        android:textSize="14sp"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="7dp"
        android:layout_marginStart="7dp"
        android:hint="Current Name" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_marginTop="11dp"
        android:id="@+id/editPass"
        android:hint="Enter Password"
        android:gravity="center_vertical|center"
        android:textSize="18sp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAllCaps="false"
        android:textStyle="normal|bold" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText5"
        android:textStyle="bold|italic"
        android:textSize="14sp"
        android:hint="New Name"
        android:layout_alignTop="@+id/button3"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignStart="@+id/editText3"
        android:layout_marginTop="32dp" />
</RelativeLayout>


main activity java :


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText Name, Pass , updateold, updatenew, delete;
    myDbAdapter helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Name= (EditText) findViewById(R.id.editName);
        Pass= (EditText) findViewById(R.id.editPass);
        updateold= (EditText) findViewById(R.id.editText3);
        updatenew= (EditText) findViewById(R.id.editText5);
        delete = (EditText) findViewById(R.id.editText6);

        helper = new myDbAdapter(this);
    }
    public void addUser(View view)
    {
        String t1 = Name.getText().toString();
        String t2 = Pass.getText().toString();
        if(t1.isEmpty() || t2.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Both Name and Password");
        }
        else
        {
            long id = helper.insertData(t1,t2);
            if(id<=0)
            {
                Message.message(getApplicationContext(),"Insertion Unsuccessful");
                Name.setText("");
                Pass.setText("");
            } else
            {
                Message.message(getApplicationContext(),"Insertion Successful");
                Name.setText("");
                Pass.setText("");
            }
        }
    }

    public void viewdata(View view)
    {
        String data = helper.getData();
        Message.message(this,data);
    }

    public void update( View view)
    {
        String u1 = updateold.getText().toString();
        String u2 = updatenew.getText().toString();
        if(u1.isEmpty() || u2.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Data");
        }
        else
        {
            int a= helper.updateName( u1, u2);
            if(a<=0)
            {
                Message.message(getApplicationContext(),"Unsuccessful");
                updateold.setText("");
                updatenew.setText("");
            } else {
                Message.message(getApplicationContext(),"Updated");
                updateold.setText("");
                updatenew.setText("");
            }
        }

    }
    public void delete( View view)
    {
        String uname = delete.getText().toString();
        if(uname.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Data");
        }
        else{
            int a= helper.delete(uname);
            if(a<=0)
            {
                Message.message(getApplicationContext(),"Unsuccessful");
                delete.setText("");
            }
            else
            {
                Message.message(this, "DELETED");
                delete.setText("");
            }
        }
    }
}


myDbAdapter.java :


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class myDbAdapter {
    myDbHelper myhelper;
    public myDbAdapter(Context context)
    {
        myhelper = new myDbHelper(context);
    }

    public long insertData(String name, String pass)
    {
        SQLiteDatabase dbb = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME, name);
        contentValues.put(myDbHelper.MyPASSWORD, pass);
        long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
        return id;
    }

    public String getData()
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] columns = {myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD};
        Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null);
        StringBuffer buffer= new StringBuffer();
        while (cursor.moveToNext())
        {
            int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
            String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
            String  password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
            buffer.append(cid+ "  " + name + "  " + password +" \n");
        }
        return buffer.toString();
    }

    public  int delete(String uname)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] whereArgs ={uname};

        int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs);
        return  count;
    }

    public int updateName(String oldName , String newName)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME,newName);
        String[] whereArgs= {oldName};
        int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs );
        return count;
    }

    static class myDbHelper extends SQLiteOpenHelper
    {
        private static final String DATABASE_NAME = "myDatabase";    // Database Name
        private static final String TABLE_NAME = "myTable";  // Table Name
        private static final int DATABASE_Version = 1;    // Database Version
        private static final String UID="_id";    // Column I (Primary Key)
        private static final String NAME = "Name";    //Column II
        private static final String MyPASSWORD= "Password";    // Column III
        private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
                " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
        private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
        private Context context;

        public myDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_Version);
            this.context=context;
        }

        public void onCreate(SQLiteDatabase db) {

            try {
                db.execSQL(CREATE_TABLE);
            } catch (Exception e) {
                Message.message(context,""+e);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            try {
                Message.message(context,"OnUpgrade");
                db.execSQL(DROP_TABLE);
                onCreate(db);
            }catch (Exception e) {
                Message.message(context,""+e);
            }
        }
    }
}


Message.java class (simplifies toast message) :


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.content.Context;
import android.widget.Toast;

public class Message {
    public static void message(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}


lv4 sunny


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: onUpgrade SQlite DB and get raw data query    Sat Jun 23, 2018 12:21 pm





onUpgrade SQlite DB and get raw data query (an upgrade to the prev walkthrough (lv4) of the SQLite DB (see above walkthrough)):


activity_main.xml :



Code:
<?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"
    tools:context=".MainActivity">

    <TextView
        android:text="username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="12dp"
        android:id="@+id/textView"
        android:textSize="18sp"
        android:textStyle="bold|italic"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:gravity="center" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editName"
        android:textStyle="bold|italic"
        android:layout_below="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Enter Name"
        android:gravity="center_vertical|center" />

    <TextView
        android:text="password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="13dp"
        android:id="@+id/textView2"
        android:textStyle="bold|italic"
        android:textSize="18sp"
        android:layout_below="@+id/editName"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:gravity="center"
        android:hint="Enter Password" />

    <Button
        android:text="view_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:textSize="18sp"
        android:onClick="viewdata"
        android:textStyle="bold|italic"
        android:layout_alignBaseline="@+id/button"
        android:layout_alignBottom="@+id/button"
        android:layout_alignRight="@+id/button4"
        android:layout_alignEnd="@+id/button4" />

    <Button
        android:text="add_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:textStyle="bold|italic"
        android:textSize="18sp"
        android:onClick="addUser"
        android:layout_marginLeft="28dp"
        android:layout_marginStart="28dp"
        android:layout_below="@+id/editPass"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="23dp" />

    <Button
        android:text="update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        android:onClick="update"
        android:textStyle="normal|bold"
        android:layout_below="@+id/editText3"
        android:layout_alignLeft="@+id/button4"
        android:layout_alignStart="@+id/button4"
        android:layout_marginTop="13dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText6"
        android:layout_alignTop="@+id/button4"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:freezesText="false"
        android:hint="Enter Name to Delete Data"
        android:layout_toLeftOf="@+id/button2"
        android:layout_toStartOf="@+id/button2" />

    <Button
        android:text="delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="21dp"
        android:layout_marginEnd="21dp"
        android:id="@+id/button4"
        android:onClick="delete"
        android:textStyle="normal|bold"
        tools:ignore="RelativeOverlap"
        android:layout_marginBottom="41dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_marginTop="47dp"
        android:id="@+id/editText3"
        android:textStyle="bold|italic"
        android:textSize="14sp"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="7dp"
        android:layout_marginStart="7dp"
        android:hint="Current Name" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_marginTop="11dp"
        android:id="@+id/editPass"
        android:hint="Enter Password"
        android:gravity="center_vertical|center"
        android:textSize="18sp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textAllCaps="false"
        android:textStyle="normal|bold" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText5"
        android:textStyle="bold|italic"
        android:textSize="14sp"
        android:hint="New Name"
        android:layout_alignTop="@+id/button3"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignStart="@+id/editText3"
        android:layout_marginTop="32dp" />
</RelativeLayout>


MainActivity.java :


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText Name, Pass , updateold, updatenew, delete;
    myDbAdapter helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Name= (EditText) findViewById(R.id.editName);
        Pass= (EditText) findViewById(R.id.editPass);
        updateold= (EditText) findViewById(R.id.editText3);
        updatenew= (EditText) findViewById(R.id.editText5);
        delete = (EditText) findViewById(R.id.editText6);

        helper = new myDbAdapter(this);
    }
    public void addUser(View view)
    {
        String t1 = Name.getText().toString();
        String t2 = Pass.getText().toString();
        if(t1.isEmpty() || t2.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Both Name and Password");
        }
        else
        {
            long id = helper.insertData(t1,t2,"hadouken@upgrade.test");
            if(id<=0)
            {
                Message.message(getApplicationContext(),"Insertion Unsuccessful");
                Name.setText("");
                Pass.setText("");
            } else
            {
                Message.message(getApplicationContext(),"Insertion Successful");
                Name.setText("");
                Pass.setText("");
            }
        }
    }

    public void viewdata(View view)
    {
        Message.message(this,helper.getRow(updateold.getText().toString()));
        /*alternative code to view
        * all data
        * stored in the SQliteDb
        * */
//        String data = helper.getData();
//        Message.message(this,data);
    }

    public void update( View view)
    {
        String u1 = updateold.getText().toString();
        String u2 = updatenew.getText().toString();
        if(u1.isEmpty() || u2.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Data");
        }
        else
        {
            int a= helper.updateName( u1, u2);
            if(a<=0)
            {
                Message.message(getApplicationContext(),"Unsuccessful");
                updateold.setText("");
                updatenew.setText("");
            } else {
                Message.message(getApplicationContext(),"Updated");
                updateold.setText("");
                updatenew.setText("");
            }
        }

    }
    public void delete( View view)
    {
        String uname = delete.getText().toString();
        if(uname.isEmpty())
        {
            Message.message(getApplicationContext(),"Enter Data");
        }
        else{
            int a= helper.delete(uname);
            if(a<=0)
            {
                Message.message(getApplicationContext(),"Unsuccessful");
                delete.setText("");
            }
            else
            {
                Message.message(this, "DELETED");
                delete.setText("");
            }
        }
    }
}


Message.java


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.content.Context;
import android.widget.Toast;

public class Message {
    public static void message(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}


myDbAdapter.java :


Code:
package com.justforum.yotamarker.sqliteoperations;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class myDbAdapter {
    myDbHelper myhelper;
    public myDbAdapter(Context context)
    {
        myhelper = new myDbHelper(context);
    }

    public long insertData(String name, String pass, String email)
    {
        SQLiteDatabase dbb = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME, name);
        contentValues.put(myDbHelper.MyPASSWORD, pass);
        contentValues.put(myDbHelper.eMail, email);
        long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
        return id;
    }

    public String getData()
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] columns = {myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD,myDbHelper.eMail};
        Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null);
        StringBuffer buffer= new StringBuffer();
        while (cursor.moveToNext())
        {
            int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
            String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
            String  password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
            String e_mail = cursor.getString(cursor.getColumnIndex(myDbHelper.eMail));
            buffer.append(cid+ "   " + name + "   " + password +" \n" + e_mail +" \n");
        }

        return buffer.toString();
    }

    public String getRow(String namae)
    {
        String result = "";
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String selection = String.format("SELECT eMail FROM myTable WHERE Name='%s'", namae);
        //String selection = "SELECT eMail FROM myTable WHERE Name='%s'";
        Cursor cursor = db.rawQuery(selection, null);
        //result = cursor.getString(cursor.getColumnIndex(myDbHelper.eMail));
        if (cursor.moveToFirst()){
            do{
                result = cursor.getString(cursor.getColumnIndex("eMail"));
                // do what ever you want here
            }while(cursor.moveToNext());
        }
        cursor.close();
        return result;
            //Cursor cursor =db.rawQuery("SELECT eMail FROM TABLE_NAME WHERE NAME = ?",new String[] {namae});
//        StringBuffer buffer= new StringBuffer();
//        int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
//        String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
//        String  password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
//        String e_mail = cursor.getString(cursor.getColumnIndex(myDbHelper.eMail));
//        buffer.append(cid+ "   " + name + "   " + password +" \n" + e_mail +" \n");
//        return buffer.toString();
    }


    public  int delete(String uname)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] whereArgs ={uname};

        int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs);
        return  count;
    }

    public int updateName(String oldName , String newName)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME,newName);
        String[] whereArgs= {oldName};
        int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs );
        return count;
    }

    static class myDbHelper extends SQLiteOpenHelper
    {
        private static final String DATABASE_NAME = "myDatabase";    // Database Name
        private static final String TABLE_NAME = "myTable";   // Table Name
        private static final int DATABASE_Version = 2;    // Database Version
        private static final String UID="_id";     // Column I (Primary Key)
        private static final String NAME = "Name";    //Column II
        private static final String MyPASSWORD= "Password";    // Column III
        private static final String eMail= "eMail";    // Column 4
        private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
                " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
        private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
        private static final String DATABASE_ALTER_DB = "ALTER TABLE "
                + TABLE_NAME + " ADD COLUMN " + eMail + " string;";

        private Context context;

        public myDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_Version);
            this.context=context;
        }

        public void onCreate(SQLiteDatabase db) {

            try {
                db.execSQL(CREATE_TABLE);
            } catch (Exception e) {
                Message.message(context,""+e);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            try {
                Message.message(context,"OnUpgrade");
                if (oldVersion < 2) {
                    db.execSQL(DATABASE_ALTER_DB);
                }

            }catch (Exception e) {
                Message.message(context,""+e);
            }
        }
    }
}


key notes :
1 private static final int DATABASE_Version = 2; // was 1 in previous ver
private static final String eMail= "eMail";    // Column 4 was added
2 add :
if (oldVersion < 2) {
                   db.execSQL(DATABASE_ALTER_DB);
               }
if (oldVersion < 3) {
                   db.execSQL(DATABASE_ALTER_DB2);
               }
add so on to run all upgrades successfully one by one.

private static final String DATABASE_ALTER_DB = "ALTER TABLE "
               + TABLE_NAME + " ADD COLUMN " + eMail + " string;";

adds email column without losing prev DB data

getData() will return all data in the db use it to see the changes between the data in prev SQDb version
to the new one, in ver 1 the email fields (didn't exist)

public long insertData(String name, String pass, String email)
was therefore, also modified :
contentValues.put(myDbHelper.eMail, email); was added

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android enable and send SMS   Thu Jun 28, 2018 2:58 pm



android enable and send SMS :

manifest :
add : <uses-permission android:name="android.permission.SEND_SMS" />
so it looks like :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.smstest1">
    <uses-permission android:name="android.permission.SEND_SMS" />

    <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>

main xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >
    </EditText>

    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="5"
        android:gravity="top" />

    <Button
        android:id="@+id/buttonSend"
        android:onClick="test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>


main java notice in the oncreate the app checks if SMS permission was enabled if not
a dialog pops up asking the user to permit SMS sending for this app, next times the permission isn't needed
(it stays permitted):

Code:
package com.justforum.yotamarker.smstest1;

import android.Manifest;
import android.content.DialogInterface;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button buttonSend;
    EditText textPhoneNo;
    EditText textSMS;
    final int SEND_SMS_PERMISSION_REQUEST_CODE =1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
        textSMS = (EditText) findViewById(R.id.editTextSMS);
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.SEND_SMS)) {

            new AlertDialog.Builder(this)
                    .setTitle("Permission needed")
                    .setMessage("This permission is needed because the app needs to be able to send SMSes")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);

    }}

    public void test(View view) {
        String phoneNo = textPhoneNo.getText().toString();
        String sms = textSMS.getText().toString();

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, sms, null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!",
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                    "SMS faild, please try again later!",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
    }
}}



SMS okute miru ka

_________________
MB over and out _______________________     


Last edited by Moti Barski on Mon Jul 09, 2018 12:12 am; edited 1 time in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android stusio summon a phone call   Sat Jun 30, 2018 8:24 am




android stusio summon a phone call

main xml :



Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/buttonCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="call"
        />

</LinearLayout>
</android.support.constraint.ConstraintLayout>


main activity java
notice this code line ("tel:replace this with phone number") to  something like ("tel:5556666666"):


Code:
package com.justforum.yotamarker.phone_call;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    /*
    * make sure you add :
    * <uses-permission android:name="android.permission.CALL_PHONE" />
    * to AndroidManifest.xml
    *        ___
      /___\
     (|0 0|)
   __/{\U/}\_ ___/vvv
  / \  {~}   / _|_P|
  | /\  ~   /_/   ||
  |_| (____)      ||
  \_]/______\   /\_||_/\
     _\_||_/_  |] _||_ [|
call (_,_||_,_) \/ [] \/
    * */
    private Button button;
    private static final int REQUEST_PHONE_CALL = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ensure enablement of phone calls
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CALL_PHONE)) {

            new AlertDialog.Builder(this)
                    .setTitle("Permission needed")
                    .setMessage("This permission is needed to make phone calls")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PHONE_CALL);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PHONE_CALL);

        }

        button = (Button) findViewById(R.id.buttonCall);
// button click event listener summons phone call :
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:0528260610"));
                if (ActivityCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                startActivity(callIntent);
            }
        });


    }


}

please read java doc in main Java.

if you are in a different java class change startActivity(callIntent);
to context.startActivity(callIntent);

context = this.context from any activity

_________________
MB over and out _______________________     


Last edited by Moti Barski on Mon Jul 09, 2018 1:39 pm; edited 6 times in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: open the developer options in galaxy s7 edge after the update :   Sat Jun 30, 2018 8:29 am

open the developer options in galaxy s7 edge after the update :
about phone
software details
tap build 7 times

Shocked

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio access phone contact list walkthrough   Wed Jul 04, 2018 9:10 am




android studio access phone contact list walkthrough

A add manifest premission :
<uses-permission android:name="android.permission.READ_CONTACTS"/>

B activity_main.xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <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"
        >
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

C add layout file in dir : res, layout : simple_list_item_1.xml  (the partinias):


Code:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:textColor="@android:color/black" />


D MainActivity java code :


Code:
package com.justforum.yotamarker.mycontacts;

import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class MainActivity extends Activity {
    private static final int REQUEST_READ_CONTACTS = 444;
    private ListView mListView;
    private ProgressDialog pDialog;
    private Handler updateBarHandler;
    ArrayList<String> contactList;
    Cursor cursor;
    int counter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Reading contacts...");
        pDialog.setCancelable(false);
        pDialog.show();
        mListView = (ListView) findViewById(R.id.list);
        updateBarHandler = new Handler();
        // Since reading contacts takes more time, let's run it on a separate thread.
        new Thread(new Runnable() {
            @Override
            public void run() {
                getContacts();
            }
        }).start();
        // Set onclicklistener to the list item.
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //TODO Do whatever you want with the list data
                Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }
    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getContacts();
            }
        }
    }
    public void getContacts() {
        if (!mayRequestContacts()) {
            return;
        }
        contactList = new ArrayList<String>();
        String phoneNumber = null;
        String email = null;
        Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
        String _ID = ContactsContract.Contacts._ID;
        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
        String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
        Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
        String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
        Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
        String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
        String DATA = ContactsContract.CommonDataKinds.Email.DATA;
        StringBuffer output;
        ContentResolver contentResolver = getContentResolver();
        cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
        // Iterate every contact in the phone
        if (cursor.getCount() > 0) {
            counter = 0;
            while (cursor.moveToNext()) {
                output = new StringBuffer();
                // Update the progress message
                updateBarHandler.post(new Runnable() {
                    public void run() {
                        pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
                    }
                });
                String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
                String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {
                    output.append("\n First Name:" + name);
                    //This is to read multiple phone numbers associated with the same contact
                    Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
                    while (phoneCursor.moveToNext()) {
                        phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                        output.append("\n Phone number:" + phoneNumber);
                    }
                    phoneCursor.close();
                    // Read every email id associated with the contact
                    Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
                    while (emailCursor.moveToNext()) {
                        email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
                        output.append("\n Email:" + email);
                    }
                    emailCursor.close();
                    String columns[] = {
                            ContactsContract.CommonDataKinds.Event.START_DATE,
                            ContactsContract.CommonDataKinds.Event.TYPE,
                            ContactsContract.CommonDataKinds.Event.MIMETYPE,
                    };
                    String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
                            " and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
                    String[] selectionArgs = null;
                    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
                    Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
                    Log.d("BDAY", birthdayCur.getCount()+"");
                    if (birthdayCur.getCount() > 0) {
                        while (birthdayCur.moveToNext()) {
                            String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
                            output.append("Birthday :" + birthday);
                            Log.d("BDAY", birthday);
                        }
                    }
                    birthdayCur.close();
                }
                // Add the contact to the ArrayList
                contactList.add(output.toString());
            }
            // ListView has to be updated using a ui thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item_1, R.id.text1, contactList);
                    mListView.setAdapter(adapter);
                }
            });
            // Dismiss the progressbar after 500 millisecondds
            updateBarHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pDialog.cancel();
                }
            }, 500);
        }
    }
}


keynotes : you can get the actual data from the variable output = new StringBuffer();
for example store it into a dictionary key = name, value = rest of the data.

or from the var : ArrayList<String> contactList; using a regex to get the string part you want per contact

2nd keynote : the main java contains code for using a thread to run code in parallal (on an additional cpu core)
which speeds up the app. clown

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android xml main attributes mini grimoire   Wed Jul 04, 2018 10:56 am

android xml main attributes mini grimoire

button :

Code:
<Button
        android:onClick="TestHelloWorld"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="63dp"
        android:text="Button" />

<!-- this is a comment -->

relative layout :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <!--place widgets in her-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
  

</android.support.constraint.ConstraintLayout>

text attributes :
android:textAlignment="center"
       android:hint="enter Item"
android:textAllCaps="false" allow caps chars
android:layout_centerHorizontal="true" center the item on the UserInterface

android:layout_centerHorizontal="true"
       android:layout_centerVertical="true" full center iten on UI

android:padding="30dp"

android:layout_marginTop="15dp"
           android:layout_marginLeft="40dp"

android:layout_toRightOf="@id/txtName" place item to right of other item

android:textAppearance="?android:attr/textAppearanceLarge" large text

android:textSize="16dp"
android:visibility="invisible"

set item size :

android:layout_width="100dp"
       android:layout_height="200dp"

LinearLayout and gravity atrribute :

Code:
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!1"
            android:id="@+id/lbl1"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!2"
            android:id="@+id/lbl2"
            android:layout_gravity="left"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!3"
            android:id="@+id/lbl3"
            android:layout_gravity="right"
            />

    </LinearLayout>

android:textColor="#a548d419" color

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio text to speech for API 21 and above (un deprecated ) walkthrough   Sat Jul 07, 2018 10:55 am




main xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/matrix3"
        >
<LinearLayout
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="200dp">
    <TextView android:id="@+id/intro"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter some text:"
        android:layout_gravity="top"
        android:textColor="#037117"
        />
    <EditText android:id="@+id/enter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="text"
        android:textColor="#037117"
        />
        />
</LinearLayout>
    <Button android:id="@+id/speak"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Speak"
        android:layout_below="@id/ll1"
        android:textColor="#037117"
        />
    </RelativeLayout>
</android.support.constraint.ConstraintLayout>

main java code :


Code:
package com.justforum.yotamarker.tts1;

import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    TextToSpeech t1;
    EditText write;
    Button speakbtn;


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

        write=(EditText) findViewById(R.id.enter);
        speakbtn=(Button)findViewById(R.id.speak);

        t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.UK);
                }
            }
        });
        speakbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String toSpeak = write.getText().toString();
                Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
                t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
            }
        });

    }
    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (t1 != null) {
            t1.stop();
            t1.shutdown();
        }
        super.onDestroy();
    }
}

notice at t1.setLanguage(Locale.UK) you can change the accent.


alternative code main java (stronger) :

Code:
package com.justforum.yotamarker.tts1;

import android.content.Intent;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements OnClickListener, OnInitListener {

    //TTS object
    private TextToSpeech myTTS;
    //status check code
    private int MY_DATA_CHECK_CODE = 0;

    //create the Activity
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //get a reference to the button element listed in the XML layout
        Button speakButton = (Button)findViewById(R.id.speak);
        //listen for clicks
        speakButton.setOnClickListener(this);

        //check for TTS data
        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
    }

    //respond to button clicks
    public void onClick(View v) {

        //get the text entered
        EditText enteredText = (EditText)findViewById(R.id.enter);
        String words = enteredText.getText().toString();
        speakWords(words);
    }

    //speak the user text
    private void speakWords(String speech) {

        //speak straight away
        /*
        *  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null, null);
        }else{
            myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null); // deprecated
        }
        * */


        myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null,null);
    }

    //act on result of TTS data check
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                //the user has the necessary data - create the TTS
                myTTS = new TextToSpeech(this, this);
            }
            else {
                //no data - install it now
                Intent installTTSIntent = new Intent();
                installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installTTSIntent);
            }
        }
    }

    //setup TTS
    public void onInit(int initStatus) {

        //check for successful instantiation
        if (initStatus == TextToSpeech.SUCCESS) {
            if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
                myTTS.setLanguage(Locale.US);
        }
        else if (initStatus == TextToSpeech.ERROR) {
            Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
        }
    }
}


hadouken  👽


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio progress dialogs walkthrough   Mon Jul 09, 2018 12:53 am

progress dialog bar and progress dialog ring :

manifest :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.progressdialog"
    android:versionCode="1"
    android:versionName="1.0"
    >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <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>

<uses-sdk
       android:minSdkVersion="8"
       android:targetSdkVersion="19" /> was added.

main xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <TextView android:id="@+id/infotext"
            android:layout_marginTop="50dp"
            android:text="Click the button to see how Progress dialog works.."
            android:layout_height="wrap_content"
            android:layout_width="match_parent"/>
        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="launchBarDialog"
            android:text="ProgressDialog Bar" />
        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="launchRingDialog"
            android:text="ProgressDialog Ring" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>


main activity java code :

Code:
package com.justforum.yotamarker.progressdialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class MainActivity extends Activity {
    ProgressDialog barProgressDialog;
    Handler updateBarHandler;
    /*
    *             //
()=========>>=========================--
            \\
    *               />
 (           //------------------------------------------------------(
(*)OXOXOXOXO(*>                  --------                             \
 (           \\--------------------------------------------------------)
              \>
    *
    * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        updateBarHandler=new Handler();
    }
    public void launchRingDialog(View view) {
        final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Downloading Image ...", true);
        ringProgressDialog.setCancelable(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Here you should write your time consuming task...
                    // Let the progress ring for 10 seconds...
                    Thread.sleep(10000);
                } catch (Exception e) {
                }
                ringProgressDialog.dismiss();
            }
        }).start();
    }
    public void launchBarDialog(View view) {
        barProgressDialog = new ProgressDialog(MainActivity.this);
        barProgressDialog.setTitle("Downloading Image ...");
        barProgressDialog.setMessage("Download in progress ...");
        barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
        barProgressDialog.setProgress(0);
        barProgressDialog.setMax(20);
        barProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Here you should write your time consuming task...
                    while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
                        Thread.sleep(2000);
                        updateBarHandler.post(new Runnable() {
                            public void run() {
                                barProgressDialog.incrementProgressBy(2);
                            }
                        });
                        if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
                            barProgressDialog.dismiss();
                        }
                    }
                } catch (Exception e) {
                }
            }
        }).start();
    }
}

each button runs a different prog bar.
place your code instead of the Thread.sleep(x);


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: free icons link   Mon Jul 09, 2018 1:05 am


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: use glide to load images from url   Mon Jul 09, 2018 1:41 am



add permission to manifest xml :

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

add implementation 'com.github.bumptech.glide:glide:4.7.1' to gradle module :

Code:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.justforum.yotamarker.urlimage"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.github.bumptech.glide:glide:4.7.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


main xml :


Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/txt1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/txt1"
        android:id="@+id/imageview1"
        android:src="@drawable/ic_launcher_background"
        />

</RelativeLayout>


</android.support.constraint.ConstraintLayout>


main java :

Code:
package com.justforum.yotamarker.urlimage;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {
ImageView iv1;
Context context = this.context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv1 = findViewById(R.id.imageview1);

        Glide.with(this).load("http://pacific.network/wp-content/uploads/2017/02/hadoken.jpg").into(iv1);
    }
}

make sure the url is correct.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: using dimen in an xml UserInterface   Mon Jul 09, 2018 1:46 pm

add : dimens.xml in res,values

Code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="edge">16dp</dimen>

</resources>



main xml :


Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_margin="@dimen/edge"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="My List"
        android:gravity="center"
        android:textSize="22sp"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Data"
        android:background="#009fff"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:id="@+id/btnAdd"
        />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myLst"/>
</LinearLayout>

the 16dp edge makes the app more comfortable to use.Wink Razz

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio speech to text walkthrough   Wed Jul 11, 2018 6:04 pm



AndroidManifest.xml :

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

activity_main.xml :

Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#000">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="16dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/mic"
            android:layout_gravity="center"
            android:id="@+id/imgMic"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="32sp"
            android:text="@string/micTap"
            android:layout_gravity="center"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"
            android:id="@+id/txtMic"
            android:textColor="#fff"/>
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lstResult"
            />
    </LinearLayout>
</LinearLayout>


string.xml (res, values directory):


Code:
<resources>
    <string name="app_name">STT</string>
    <string name="micTap">Tap Mic for command</string>
    <string name="permission_denied">permission denied</string>
    <string name="recIntent">Speak to phone</string>
</resources>


MainActivity.java :

Code:
package com.justforum.yotamarker.stt1;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private TextView txtDesc;
    private ImageView imgMic;
    private ListView lstRes;
    private Context context;
    private boolean hasAudioPermission = false;

    private final int REQUEST_CODE = 1;
    private final int RECOGNITION_RESULT = 2;

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

    private void askPermission() {
        //create a list of permissions
        List<String> listPerm = new ArrayList<>(); // contains the recog results per talk
        //get permission status for audio record
        int audioPerm = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO);
        //check if the record audio permission is granted
        if (audioPerm != PackageManager.PERMISSION_GRANTED) {
            listPerm.add(Manifest.permission.RECORD_AUDIO);
        } else {
            hasAudioPermission = true;
        }

        //check if our list is not empty, and ask permission for it's items.
        if (!listPerm.isEmpty()) {
            //ask permission by requests.
            ActivityCompat.requestPermissions(this, listPerm.toArray(new String[listPerm.size()]), REQUEST_CODE);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //we can do what ever we like.
                hasAudioPermission = true;
            } else {
                //tell the user that we can't work, becuase we don't have a permission
                Toast.makeText(context, getResources().getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void setPointer() {
        this.context = this;
        txtDesc = findViewById(R.id.txtMic);
        imgMic = findViewById(R.id.imgMic);
        lstRes = findViewById(R.id.lstResult);
        imgMic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runSpeechRecognition();
            }
        });
    }

    private void runSpeechRecognition() {
        //handle the speech recognition intent
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        //tell the intent that we want to speak freely
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        //tell the intent that we want to use the default language
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
        //show the user a text to explain what we want.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getResources().getString(R.string.recIntent));
        if (hasAudioPermission) {
            try {
                startActivityForResult(intent, RECOGNITION_RESULT);
            } catch (ActivityNotFoundException e) {
                Log.e("err", "runSpeechRecognition: " + e.getMessage());
                Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e("WTF", "runSpeechRecognition: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //in case the request code is 2 - recognition intent
            case RECOGNITION_RESULT:
                if (resultCode == RESULT_OK && data != null)
                {
                    //get array list of all our result (can be 1, can be 5)
                    ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    LangAdapter myAdapter = new LangAdapter(context,result);
                    lstRes.setAdapter(myAdapter);
                }
                break;

            default:
                Toast.makeText(context, "the programmer is not so bright", Toast.LENGTH_SHORT).show();
        }
    }
}

add : mic.png to res, drawable

LangAdapter.java :

Code:
package com.justforum.yotamarker.stt1;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class LangAdapter extends BaseAdapter {
    Context context;
    ArrayList<String> myResult;

    public LangAdapter(Context context, ArrayList<String> myResult) {
        this.context = context;
        this.myResult = myResult;
    }

    @Override
    public int getCount() {
        return myResult.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(context);
        txt.setText(myResult.get(position));
        txt.setTextColor(Color.WHITE);
        return txt;
    }
}

key note :
access the result :
String x = result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length()) + "";
place it in : onActivityResult in switch (requestCode) in if (resultCode == RESULT_OK && data != null)
{
(line 131)

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android special toast   Sat Jul 14, 2018 1:59 am




Add dependency in your app module
dependencies {
implementation 'com.sdsmdg.tastytoast:tastytoast:0.1.1'
}

Usage
Java
TastyToast.makeText(getApplicationContext(), "Hello World !", TastyToast.LENGTH_LONG, TastyToast.WARNING);

example code for main java :

Code:
package com.justforum.yotamarker.tastytoast;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.sdsmdg.tastytoast.TastyToast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TastyToast.makeText(getApplicationContext(), "Hello World !", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
        // type TastyToast. at TastyToast.SUCCESS to see more options
    }
}

special toast

_________________
MB over and out _______________________     


Last edited by Moti Barski on Tue Jul 24, 2018 6:22 pm; edited 1 time in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android xml and json from url parse   Sun Jul 15, 2018 6:20 pm

r

the following app parses the relevant data fields from an xml and json file :
json code path :
getDATAJSON()

xml path :
setPointer();
       //get my data - XML
       getDataXML();

and displays on the listview (which uses the adapter which uses the clscur java class)

main xml :


Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myLst"/>

</LinearLayout>


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

MainActivity.java :


Code:
package com.justforum.yotamarker.jsonplusxml;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends AppCompatActivity {

    private List<ClsCur> myCurList;
    private String xmlString = "";
    private String jsonString = "";
    private final String XML_URL = "http://www.boi.org.il/currency.xml";
    private final String JSON_URL = "https://api.darksky.net/forecast/f13189b34ee908d0e07ba487133fa847/32.0844224,34.8029073";
    private Context context;
    ListView lstCur;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setPointer();
        //get my data - XML
        getDataXML();
        getDataJSON();

    }

    private void setPointer() {
        this.context = this;
        myCurList = new ArrayList<>();
        lstCur = findViewById(R.id.myLst);

    }

    @SuppressLint("StaticFieldLeak")
    public void getDataXML() {
        //we never use void in AsyncTask, we need to use Void
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                //we need to open HTTP URL Connection to our desired URL (www.boi.org.il)
                HttpURLConnection connection = null;
                try {
                    connection = (HttpURLConnection) new URL(XML_URL).openConnection();
                    BufferedReader buf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = buf.readLine()) != null) {
                        xmlString += line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    connection.disconnect();
                }

                return xmlString;
            }

            @Override
            protected void onPostExecute(String xmlString) {
                super.onPostExecute(xmlString);
                Log.e("XML", "onPostExecute: " + xmlString);
                parseXML(xmlString);
            }
        }.execute();
    }

    private void parseXML(String xmlString) {
        //we will create a document builder that will allow us an easier access to our XML String
        DocumentBuilder builder;
        try {
            Log.e("XML", "onPostExecute: " + xmlString);
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document DOM = builder.parse(new InputSource(new StringReader(xmlString)));

            //our xml structure
            NodeList itemName = DOM.getElementsByTagName("NAME");
            NodeList itemUnit = DOM.getElementsByTagName("UNIT");
            NodeList itemCur = DOM.getElementsByTagName("CURRENCYCODE");
            NodeList itemCountry = DOM.getElementsByTagName("COUNTRY");
            NodeList itemRate = DOM.getElementsByTagName("RATE");
            NodeList itemChange = DOM.getElementsByTagName("CHANGE");

            //let got on our entire collection to get the data
            for (int counter = 0; counter < itemName.getLength(); counter += 1) {
                myCurList.add(new ClsCur(
                        itemName.item(counter).getTextContent(),
                        Integer.parseInt(itemUnit.item(counter).getTextContent()),
                        itemCur.item(counter).getTextContent(),
                        itemCountry.item(counter).getTextContent(),
                        Float.parseFloat(itemRate.item(counter).getTextContent()),
                        Float.parseFloat(itemChange.item(counter).getTextContent())
                ));
            }
            Adapter_Cur myAdapter = new Adapter_Cur(context, myCurList);
            lstCur.setAdapter(myAdapter);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }

    @SuppressLint("StaticFieldLeak")
    public void getDataJSON() {
        //we never use void in AsyncTask, we need to use Void
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                //we need to open HTTP URL Connection to our desired URL (www.boi.org.il)
                HttpURLConnection connection = null;
                try {
                    connection = (HttpURLConnection) new URL(JSON_URL).openConnection();
                    BufferedReader buf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = buf.readLine()) != null) {
                        jsonString += line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    connection.disconnect();
                }

                return jsonString;
            }

            @Override
            protected void onPostExecute(String jsonString) {
                super.onPostExecute(jsonString);
                Log.e("XML", "onPostExecute: " + jsonString);
                parseJson(jsonString);
            }
        }.execute();
    }

    private void parseJson(String jsonString) {
        //declaring the json object and passing the string to it.
        try {
            //get the entire string and treat it as a JSON object
            JSONObject jsonObject = new JSONObject(jsonString);
            //get the currently object
            JSONObject currently = jsonObject.getJSONObject("currently");
            Log.e("currently", "parseJson: "+currently );
            //get the summry which is a string.
            String summary = currently.getString("summary");
            //get the temp.
            Double temp = currently.getDouble("temperature");
            // f->c
            int tempC=(int)(((temp-32)*(5/9.0))*100)/100;
            int hum=(int)(currently.getDouble("humidity")*100);
            String display = "summary:"+summary+" tempC:"+tempC+"Cel. humidity:"+hum+"%";
            Log.e("JSON", "parseJson: "+display );
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Adapter_Cur java (4 D xml listview):

Code:
package com.justforum.yotamarker.jsonplusxml;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

public class Adapter_Cur extends BaseAdapter {
    Context context;
    List<ClsCur> lstCur;

    public Adapter_Cur(Context context, List<ClsCur> lstCur) {
        this.context = context;
        this.lstCur = lstCur;
    }

    @Override
    public int getCount() {
        return lstCur.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(context);
        txt.setText(lstCur.get(position).getCountry() + " " +
                lstCur.get(position).getRate() + " " +
                lstCur.get(position).getChange());
        return txt;
    }
}

ClsCur java class (stores the xml data):


Code:
package com.justforum.yotamarker.jsonplusxml;

public class ClsCur {
    private String name;
    private int unit;
    private  String currencycode;
    private String country;
    private float rate;
    private float change;

    public ClsCur(String name, int unit, String currencycode, String country, float rate, float change) {
        this.name = name;
        this.unit = unit;
        this.currencycode = currencycode;
        this.country = country;
        this.rate = rate;
        this.change = change;
    }

    public String getName() {
        return name;
    }

    public int getUnit() {
        return unit;
    }

    public String getCurrencycode() {
        return currencycode;
    }

    public String getCountry() {
        return country;
    }

    public float getRate() {
        return rate;
    }

    public float getChange() {
        return change;
    }
}

xml & json parse
https://jsoneditoronline.org/

_________________
MB over and out _______________________     


Last edited by Moti Barski on Mon Jul 23, 2018 3:44 pm; edited 3 times in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: cardview on recycler view   Sat Jul 21, 2018 9:45 am



add :
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
to gradle module so it looks like :

Code:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId ""
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support:cardview-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

res/layout :
activity_main xml :

Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


res/layout/item.xml (the recycler item with the card view) :

Code:
<?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/myItem"
        style="@style/Base.CardView"
        android:layout_gravity="center"
        android:layout_margin="16dp"
        android:animateLayoutChanges="?android:attr/windowOverscan"
        android:elevation="10dp"
        app:cardCornerRadius="20dp"
        app:contentPadding="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layoutDirection="locale">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/txtName"
                android:layout_alignParentTop="true"
                android:text="אלכס טזי"
                android:textColor="#0f0"
                android:textSize="26sp"
                android:textStyle="bold|italic"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/txtSlogan"
                android:layout_below="@id/txtName"
                android:layout_marginTop="10dp"
                android:shadowColor="@color/cardview_shadow_start_color"
                android:shadowDx="10"
                android:shadowDy="10"
                android:text="אלכס חבר של הפקח, סמי סביב"
                android:textColor="#00f"
                android:textSize="18sp"
                />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentBottom="true"
                android:text="delete"
                android:id="@+id/btnMoti"
                />
        </RelativeLayout>

    </android.support.v7.widget.CardView>
</LinearLayout>

DataObject.java :
(constructor and getters constructed with alt + insert)

Code:
public class DataObject {
    private String mText1;
    private String mText2;

    public DataObject(String mText1, String mText2) {
        this.mText1 = mText1;
        this.mText2 = mText2;
    }

    public String getmText1() {
        return mText1;
    }

    public String getmText2() {
        return mText2;
    }
}


MyRecyclerViewAdapter :


Code:
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {

    //set title for our tag
    private final String TAG="RecyclerView Adapter";
    //our data set list
    private List<DataObject>lstDataSet;
    //create interface for click listener
    public interface MyClickListener{
        void onItemClick(int position, View v);
    }
    //our click listener that will be sent by method (interface)
    private MyClickListener myClickListener;

    //our c'tor to our class :)
    public MyRecyclerViewAdapter(List<DataObject> lstDataSet) {
        this.lstDataSet = lstDataSet;
    }

    public class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener
    {
        TextView victimName;
        TextView victimSlogan;
        Button btnDel;
        //c'tor for our internal class which work as:
        //1. set pointer
        //2. set on click listener to our entire item.
        public DataObjectHolder(View itemView)
        {
            super(itemView);
            victimName=itemView.findViewById(R.id.txtName);
            victimSlogan=itemView.findViewById(R.id.txtSlogan);
            btnDel=itemView.findViewById(R.id.btnMoti);
            itemView.setOnClickListener(this);
        }

        //because we declare interface as implementation of on click listener, we can add some extra
        //information to our onclick.
        //since we using the method getAdapterPosition(), which give us the index of the position
        //now we hold the position and the view, instead of holding only the view without the position
        @Override
        public void onClick(View v) {
            myClickListener.onItemClick(getAdapterPosition(),v);
        }
    }

    //using the interface we set on click listener but for single item
    public void setOnItemClickListener(MyClickListener myClickListener)
    {
        this.myClickListener=myClickListener;
    }

    //create a view holder, which will be created upon using it
    @NonNull
    @Override
    public DataObjectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //inflate our card view row layout
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        //set the inflated view to our holder
        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        //return the data object holder
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull DataObjectHolder holder, final int position) {
        //set the label (our header which show index : XX)
        holder.victimName.setText(lstDataSet.get(position).getmText1());
        //set the slogan
        holder.victimSlogan.setText(lstDataSet.get(position).getmText2());
        //set delete button inside the card view
        holder.btnDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lstDataSet.remove(position);
                notifyItemRemoved(position);
            }
        });
        Log.e(TAG, "onBindViewHolder: "+lstDataSet.get(position).getmText1());
    }

    @Override
    public int getItemCount() {
        return lstDataSet.size();
    }


    //CRUD
    public void addItem(DataObject dataObject, int index)
    {
        lstDataSet.add(index,dataObject);
        notifyItemInserted(index);
    }

    public void deleteItem(int index)
    {
        lstDataSet.remove(index);
        notifyItemRemoved(index);
    }


}

MainActivity.java :


Code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private String[] victimName={"Zeev","Amital","Nipo","Buf","Sami","Eitan"};
    private String[] victimSlogan={"hadoken","I from Chabad","I want to see asuka kazama ","Where is Alex Tazi","Move your car","Tell me when you land"};

    //create a recycler view object
    private RecyclerView myRecyclerView;
    //create an (inner class) adapter for the recycler view
    private RecyclerView.Adapter myAdapter;
    //create a recycler view layout manager
    private RecyclerView.LayoutManager myLayoutManager;

    //our add button
    Button btnAdd;

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

    private void setPointer() {
        //set pointer to recycler view
        myRecyclerView = findViewById(R.id.myList);
        //set fixed size for the item
        myRecyclerView.setHasFixedSize(true);
        //create a linear layout manager
        myLayoutManager = new LinearLayoutManager(this);
        //set our layout manger to our recycler view
        myRecyclerView.setLayoutManager(myLayoutManager);
        //create an adapter
        myAdapter=new MyRecyclerViewAdapter(getDataSet());
        //set the adapter
        myRecyclerView.setAdapter(myAdapter);
        btnAdd=findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MyRecyclerViewAdapter)myAdapter).addItem(new DataObject("Bri Chakala","Nagsti ba gamba"),1);
            }
        });
    }

    private List<DataObject> getDataSet() {
        List<DataObject> returnList = new ArrayList<>();
        for (int counter=0;counter<victimName.length;counter+=1)
        {
            returnList.add(new DataObject(victimName[counter],victimSlogan[counter]));
        }
        return returnList;
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        ((MyRecyclerViewAdapter)myAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                //((MyRecyclerViewAdapter)myAdapter).deleteItem(position);
                Toast.makeText(v.getContext(), position + "", Toast.LENGTH_LONG).show();
            }
        });
    }

}


in public void onItemClick(int position, View v) { in main activity java :
you place the onclick events. Sleep

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android menu on the action bar   Sun Jul 22, 2018 6:20 pm

main java :

Code:
package com.justforum.yotamarker.menu1;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private int groupID= Menu.FIRST;
    private final int TEXT_ID = Menu.FIRST;
    private final int IMAGE_ID = Menu.FIRST+1;
    private final int VIDEO_ID = Menu.FIRST+2;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(groupID, TEXT_ID, TEXT_ID,"text");
        menu.add(groupID, IMAGE_ID, IMAGE_ID,"image");
        menu.add(groupID, VIDEO_ID, VIDEO_ID,"video");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // the onClick item event
        switch (item.getItemId())
        {
            case TEXT_ID:
                Toast.makeText(this, "text", Toast.LENGTH_SHORT).show();
                break;

            case VIDEO_ID:
                Toast.makeText(this, "video", Toast.LENGTH_SHORT).show();
                break;

            case IMAGE_ID:
                Toast.makeText(this, "image", Toast.LENGTH_SHORT).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }
}

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android burger view on action bar menu   Mon Jul 23, 2018 11:47 am




choose navigation drawer activity when starting a new project.

the click events will be in the main activity in public boolean onNavigationItemSelected(MenuItem item) {


change the text and other text attributes from res folder : menu or layout folder in the xml files


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: Re: android mobile app dev APK   Mon Jul 23, 2018 12:32 pm




to remove the action bar from all activities: change :

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to :
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

to remove action bar from a certain activity
in AndroidManifest.xml :

change : per activity :
<activity android:name=".SignUpActivity"
android:theme="@style/AppTheme.NoActionBar"/>


In your AndroidManifest.xml use NoActionBar theme for your Activity like this:
<activity android:name=".SignUpActivity"
android:theme="@style/AppTheme.NoActionBar"/>


and in your styles.xml
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>

so it looks like :

Code:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

</resources>

and manifest looks like :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.btg">
    <uses-permission android:name="android.permission.INTERNET"/>
    <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"
            android:theme="@style/AppTheme.NoActionBar"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


you can alternatively do it by code :

from within your activity:
getActionBar().hide();
or
getSupportActionBar().hide();

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: using other apps to share stuff   Mon Jul 23, 2018 1:31 pm

Code:
import android.content.Context;
import android.content.Intent;

public class Motti {
    Intent shareIntent;
    Context context;
    String myType;

    public Motti(Context context, String mimeType) {
        this.context=context;
        this.myType=mimeType;
    }

    public void startChooser()
    {
        //intent for sending action (like send image,audio,video,etc...)
        shareIntent = new Intent(Intent.ACTION_SEND);
        //set mime type
        shareIntent.setType(myType+"/*");
        //tell the user what you want to do....
        shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Moti want's to share");
        //what i want to share (for example a text)
        shareIntent.putExtra(Intent.EXTRA_TEXT,"Hello from motti :)");
        //set a package
        http://shareIntent.setPackage("com.whatsapp");
        //start activity :)
        context.startActivity(Intent.createChooser(shareIntent,"Send moti with:"));
    }
}

using the class :
Motti x = new Motti(this.getApplicationContext(),"text");
x.startChooser();

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android splash screen stand alone ver walkthrough   Wed Jul 25, 2018 5:36 pm




res/layout/splash.xml :

Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Moti is loading"
        android:textSize="32sp"
        android:layout_gravity="center"/>

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

SplashScreen.java :

Code:
package com.justforum.yotamarker.splash2;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

public class SplashScreen extends AppCompatActivity {

    // duration of wait
    private final int SPLASH_DISPLAY_LENGTH = 3000;

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(SplashScreen.this,MainActivity.class));
                SplashScreen.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

AndroidManifest.xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.splash2">

    <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" />


            </intent-filter>
        </activity>
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


keynote : in manifest took <category android:name="android.intent.category.LAUNCHER" /> from main activity and put it in
<activity android:name=".SplashScreen">

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android vibrator service   Thu Jul 26, 2018 1:22 am



add manifest permission :
<uses-permission android:name="android.permission.VIBRATE"/>

main layout xml:

Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="#009fff"
        android:text="Vibrate me"
        android:textColor="#fff"
        android:textSize="22sp"
        android:id="@+id/btnVibrate"/>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lstWifi"/>
</LinearLayout>

MainActivity.java


Code:
package com.justforum.yotamarker.myvibrator;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.Vibrator;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button btnVibrate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setPointer();
    }

    private void setPointer() {
        this.btnVibrate=findViewById(R.id.btnVibrate);
        final Vibrator vib = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        btnVibrate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vibrate(5000, vib);
            }
        });
    }

    private void vibrate(int i, Vibrator v1) {

        v1.vibrate(i); //vibrate for 500 milliseconds
    }
}

make sure you enable vibration from your phone settings.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android wifi service   Thu Jul 26, 2018 2:03 am



manifest permissions :
Code:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

activity_main.xml :

Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_margin="16dp"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="#009fff"
        android:text="Scan wi-fi"
        android:textColor="#fff"
        android:textSize="22sp"
        android:id="@+id/btnWifiScan"/>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lstWifi"/>
</LinearLayout>

WifiAdapter.java (for the list widgt containing the available wifi list) :

Code:
package com.justforum.yotamarker.mywifi;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

public class WifiAdapter extends BaseAdapter {
    Context context;
    List<String> ssid;

    public WifiAdapter(Context context, List<String> ssid) {
        this.context = context;
        this.ssid = ssid;
    }

    @Override
    public int getCount() {
        return ssid.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(context);
        txt.setText(ssid.get(position));
        txt.setTextSize(32);
        return txt;
    }
}


main java :


Code:
package com.justforum.yotamarker.mywifi;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    Button btnWifi;
    ListView lstView;
    Context context;
    final int ACCESS_FINE_LOCATION =1;
    final int ACCESS_COARSE_LOCATION =1;
    WifiManager wifi; //a manger for all our wifi requests

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

    private void setPointer() {
        this.context=this;
        this.lstView=findViewById(R.id.lstWifi);
        this.btnWifi=findViewById(R.id.btnWifiScan);
        getWifiPermission();
        btnWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanWifi();
            }
        });
    }

    private void getWifiPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            new AlertDialog.Builder(this)
                    .setTitle("gps Permission needed to scan available wifi")
                    .setMessage("This permission is needed because the app needs to be able to scan wifi")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);

        }

}

    private void scanWifi() {
        //wifi example -> pointer to system service WIFI
        wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled())
        {
            getWifiList();
        }
    }

    private void getWifiList() {
        List<ScanResult> wifiList = wifi.getScanResults();
        List<String> foundSSID = new ArrayList<>();
        for (ScanResult item:wifiList)
        {
            foundSSID.add(item.SSID);
        }
        WifiAdapter myAdapter = new WifiAdapter(context,foundSSID);
        lstView.setAdapter(myAdapter);
    }


}


4 wifi scan walkthrough look up

_________________
MB over and out _______________________     


Last edited by Moti Barski on Fri Jul 27, 2018 7:25 am; edited 1 time in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android custom service   Thu Jul 26, 2018 2:22 am



add : <service android:name=".MyCustomService"/> to the manifest above application
so it looks like :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.mycustomservice">

    <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>
        <service android:name=".MyCustomService"/>
    </application>

</manifest>


main xml :


Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#26ff00"
        android:layout_marginTop="20dp"
        android:id="@+id/btnStart"
        android:text="Start Service"
        android:textSize="32sp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff2036"
        android:layout_marginTop="20dp"
        android:id="@+id/btnStop"
        android:text="Stop Service"
        android:textSize="32sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="30dp"
        android:id="@+id/lnrLoading"
        android:visibility="invisible">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Loading some data"
            android:textSize="64sp"
            android:gravity="center"/>
        <ProgressBar
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>

MyCustomService.java

Code:
package com.justforum.yotamarker.mycustomservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.View;

public class MyCustomService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MainActivity.lnrLoading.setVisibility(View.VISIBLE);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        MainActivity.lnrLoading.setVisibility(View.INVISIBLE);
        super.onDestroy();
    }
}

main activity java :


Code:
package com.justforum.yotamarker.mycustomservice;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
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.LinearLayout;

public class MainActivity extends AppCompatActivity {
    private Button btnStart, btnStop;
    public static LinearLayout lnrLoading;
    Intent myService;

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

    private void setPointer() {
        myService = new Intent(this,MyCustomService.class);
        btnStart=findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isMyServiceRunning(MyCustomService.class)) {

                    startService(myService);
                }
            }
        });

        btnStop=findViewById(R.id.btnStop);
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMyServiceRunning(MyCustomService.class)) {
                    stopService(myService);
                }
            }
        });
        lnrLoading=findViewById(R.id.lnrLoading);
    }

    private boolean isMyServiceRunning(Class<?> serviceClass)
    {
        //create activity manager to get all process that are running in the system
        ActivityManager manger = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        //go on entire collection and check if there is a matching name to the serviceClass name
        //that we gave in the args.
        for (ActivityManager.RunningServiceInfo service:manger.getRunningServices(Integer.MAX_VALUE))
        {
            //if we found, return true
            if (serviceClass.getName().equals(service.service.getClassName()))
            {
                Log.e("onStop", "onClick: start" );
                return true;
            }
        }
        //if we didn't found , return false as a default
        return false;
    }



}


keynote : notice in main activity the code snippet :


Code:
private boolean isMyServiceRunning(Class<?> serviceClass)
    {
        //create activity manager to get all process that are running in the system
        ActivityManager manger = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        //go on entire collection and check if there is a matching name to the serviceClass name
        //that we gave in the args.
        for (ActivityManager.RunningServiceInfo service:manger.getRunningServices(Integer.MAX_VALUE))
        {
            //if we found, return true
            if (serviceClass.getName().equals(service.service.getClassName()))
            {
                Log.e("onStop", "onClick: start" );
                return true;
            }
        }
        //if we didn't found , return false as a default
        return false;
    }


it is useful for other apps using services

_________________
MB over and out _______________________     
Back to top Go down
View user profile
 
android mobile app dev APK
Back to top 
Page 2 of 3Go to page : Previous  1, 2, 3  Next
 Similar topics
-
» [Hỏi đáp] Làm sao vào giao diện mobile trên pc
» Licensed VPS[sale/Rent]+UAE Unblock Mobile dialer
» UAE Anti blocking pc2phone & mobile dialer for Rent/Purchase
» VPS with relay server based PC2Phone & mobile dialer at $499
» Mobile dialer certified by NOIKA for sale/Rent

Permissions in this forum:You cannot reply to topics in this forum
battle programmers alliance :: battle programming alliance :: battle programming-
Jump to: