battle programmers alliance

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

Display results as :
 
Rechercher Advanced Search
Latest topics
» android mobile app dev APK
Sun Jul 15, 2018 6:20 pm by Moti Barski

» android studio execises
Mon Jul 09, 2018 1:43 pm by Moti Barski

» problem with firebase authentication
Thu Jun 28, 2018 9:52 am by Moti Barski

» text art canvas
Wed Jun 20, 2018 8:55 pm by Moti Barski

» links/suggestions to become a programmer
Mon May 07, 2018 11:01 pm by Moti Barski

» java eclipse oxygen grimoire
Thu May 03, 2018 8:24 pm by Moti Barski

» forum logo by tf monkey
Wed May 02, 2018 10:17 pm by Moti Barski

» java and MySQL
Mon Apr 30, 2018 3:02 pm by Admin

» mini A.I puzzles
Mon Apr 23, 2018 11:38 am by Moti Barski

July 2018
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
293031    
CalendarCalendar
Social bookmarking
Social bookmarking digg  Social bookmarking delicious  Social bookmarking reddit  Social bookmarking stumbleupon  Social bookmarking slashdot  Social bookmarking yahoo  Social bookmarking google  Social bookmarking blogmarks  Social bookmarking live      

Bookmark and share the address of battle programmers alliance on your social bookmarking website
Share | 
 

 android mobile app dev APK

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

avatar

Posts : 154
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 : 154
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 : 154
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 : 154
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 : 154
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 : 154
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 : 154
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 : 154
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 : 154
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  alien


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

avatar

Posts : 154
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 : 154
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 : 154
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 : 154
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 : 154
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 : 154
Join date : 2011-08-02

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




Add dependency in your app module
dependencies {
compile '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
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 154
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



_________________
MB over and out
Back to top Go down
View user profile
 
android mobile app dev APK
Back to top 
Page 2 of 2Go to page : Previous  1, 2
 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: