Friday, August 31, 2018

Async Task example Counter

package net.samaysoftware.listviewdemo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class DemoThreading extends AppCompatActivity {

    TextView tvCounter;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo_threading);
        tvCounter = (TextView) findViewById(R.id.tvCounter);

        // call asynctask
        MyTask t = new MyTask();
        t.execute(10);


    }
    class MyTask extends AsyncTask<Integer, Integer, String>{

        @Override        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override        protected String doInBackground(Integer... arr) {
            int value = arr[0];
            for(int i =0; i<value;i++){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress(i+1);
            }
            return "Done";
        }



        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);


        }

        @Override        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            int v = values[0];
            tvCounter.setText(v+"");
        }
    }
}

jQuery basics


jQuery - lightweight, "write less, do more", JavaScript library

jQuery Core - jQuery UI - jQuery Mobile – QUnit - Sizzle

jQuery Features
Html/Dom Traversal & Manipulation
CSS Manipulation
Event Handling
Effects & Animations
AJAX

Install: head + script + src

Syntax: $(selector).action()
$ = access jQuery
Selector = a query to find HTML elements
Action = action to be performed on the selected elements

$(document).ready(function(){
});


SELECTORS
$(document).ready(function(){
$("p").hide();
$("#test").hide();
$(".test").hide();
});


jQuery EVENTS
Mouse Events
Keyboard Events
Form Events
Document/Window Events
click
keypress
submit
load
dblclick
keydown
change
resize
mouseenter / mouseleave
keyup
focus
scroll
mouseover / mouseout

blur
unload
mousedown / mouseup
select
ready
mousemove
hover

Click
$("#dv2 ").click(function(){
$(this).hide();
});

Hover
$("#p1").hover(
function(){alert("You entered p1!");},
function(){alert("Bye! You now leave p1!");}
);


jQuery Effects

HIDE/SHOW
$(selector).hide(speed, callback); //speed milliseconds (or “slow”, “fast”), callback function
$(selector).show(speed, callback);
$(selector).toggle(speed, callback);

FADE
$(selector). fadeIn (speed, callback);
$(selector). fadeOut (speed, callback);
$(selector). fadeToggle (speed, callback);
$(selector). fadeTo (speed, Opacity, callback);

SLIDE
$(selector). slideUp (speed, callback);   - same as hide, just effect is different
$(selector). slideDown (speed, callback);
$(selector). slideToggle (speed, callback);

ANIMATE
$(selector).animate({params},speed,callback);
$(selector).stop(stopAll,goToEnd);

e.g. $(‘.button’).click(function(){
                $(this).animate({‘width’:’200px’, ‘height’:’80px’}, 100, function(){ alert(‘done’) });
});

speed is optional, callback is optional

METHOD CHAINING
$("#p1"). slideUp(2000).slideDown(2000);

GET
$(selector).text(); //>> Text content
$(selector).html(); //>> HTML content
$(selector).val(); //>> Form Element
$(selector).attr(“href”);

SET
$(selector).text(“Hello”); //>> Text content
$(selector).html(“<div>Hello</div>”); //>> HTML content
$(selector).val(“Upanish”); //>> Form Element
$(selector).attr(“href”, “http://www.samaysoftware.net”);

ADD
$(selector).append(“</br>Last Line”); //>> append to content of the selected element
$(selector).prepend(“</br>First Line”);

$(selector).after(“<div>Last Line</div>”); //>> add this AFTER the selected element
$(selector).before(“</br>First Line”); //>> add this BEFORE the selected element

HEIRARCHY

$(“ul”).children().css(‘border-color’:’red’); -> Applies to all “li” which are within ul
$(“.p”).first().css(‘border-color’:’red’); -> Applies to 1st element whose class is p, - last()
next() -> next element after selected element  -  prev()
parent() -> immediate parent of selected element



REMOVE
.remove() - .empty()

CSS
.addClass(“”) – .removeClass(“”) – .toggleClass(“”)
.css(“propertyname”) //>> Get Value
.css(“propertyname”, “value”) //>> Set Value
.css({"propertyname":"value","propertyname":"value",...});


DIMENSIONS
width() - height() - innerWidth() - innerHeight() - outerWidth() - outerHeight()

jQuery AJAX

$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt, statusTxt, xhr){
if(statusTxt=="success")
alert("External content loaded successfully!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});


$("button").click(function(){
$.get("demo_test.asp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});

$("button").click(function(){
$.post("demo_test_post.asp",
{
name:"Donald Duck",
city:"Duckburg
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});



Web Connectivity from Android

You need 2 reference files for connecting to any webserver

HttpManager.java

RequestPackage.java

Download the above mentioned files and paste them in Android Studio

Tuesday, August 28, 2018

File Manager Code

package net.samaysoftware.sampleapplication12345;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
public class FMMainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    ListView lv;
    String[] from = {"fname","ftype"};
    int[] to = {android.R.id.text1, android.R.id.text2};
    ArrayList<HashMap<String, String>> data = new ArrayList<>();
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fmmain);
        lv = (ListView) findViewById(R.id.fmlv);
        generateData();
        SimpleAdapter sa = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,from, to);
        lv.setAdapter(sa);
        lv.setOnItemClickListener(this);
    }
    private void generateData() {
        File froot = null;
        if(getIntent().getStringExtra("abcd")==null) {
            froot = Environment.getExternalStorageDirectory();
        }
        else{
            String fpath = getIntent().getStringExtra("abcd");
            froot = new File(fpath);
            setTitle(froot.getName());
        }
        File[] arr = froot.listFiles();
        for(File f: arr){
            String name = f.getName();
            String type = f.isFile()?"File":"Folder";
            HashMap<String, String> map = new HashMap<>();
            map.put("fname", name);
            map.put("ftype", type);
            map.put("fpath", f.getAbsolutePath());
            data.add(map);
        }
    }

    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        String fpath = data.get(pos).get("fpath");
        File cf = new File(fpath);
        if(cf.isDirectory()){
            Intent i = new Intent(this, FMMainActivity.class);
            i.putExtra("abcd", fpath);
            startActivity(i);
        }else{

        }

    }
}


Note: Add permission in Manifest file as below:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
just before the <application> tag and inside the <manifest> tag.





Saturday, August 11, 2018

Static ListView with SimpleAdapter

package net.samaysoftware.listviewdemo;

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

import java.util.ArrayList;
import java.util.HashMap;

public class AnotherListViewActivity extends AppCompatActivity {

    ListView lvAnother;
    String[] from = {"a","b"};
    int[] to = {R.id.tvState, R.id.tvCapital};
    ArrayList<HashMap<String, String>> data = new ArrayList<>();

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_list_view);
        lvAnother = (ListView) findViewById(R.id.lvanother);

        prepareData();
        SimpleAdapter sa = new SimpleAdapter(this, data, R.layout.repeating_unit_2_items,from, to);
        lvAnother.setAdapter(sa);


    }

    private void prepareData() {
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("a", "Gujarat");
        map1.put("b", "Gandhinagar");

        HashMap<String, String> map2 = new HashMap<>();
        map2.put("a", "Rajasthan");
        map2.put("b", "Jaipur");

        HashMap<String, String> map3 = new HashMap<>();
        map3.put("a", "Maharasthra");
        map3.put("b", "Mumbai");

        HashMap<String, String> map4 = new HashMap<>();
        map4.put("a", "Madhyapradesh");
        map4.put("b", "Bhopal");

        data.add(map1);
        data.add(map2);
        data.add(map3);
        data.add(map4);


    }
}

ListView with ArrayAdapter (Dynamic)

package net.samaysoftware.listviewdemo;

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

import java.util.ArrayList;

public class CityListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    ListView lvCities;
    ArrayList<String> arr = new ArrayList<>();
    EditText etCityName;
    Button btnSave;
    ArrayAdapter<String> aa;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findAllViews();
        aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,arr);
        lvCities.setAdapter(aa);
        lvCities.setOnItemClickListener(this);
        btnSave.setOnClickListener(this);
    }

    private void findAllViews() {
        lvCities = (ListView) findViewById(R.id.lvCities);
        etCityName = (EditText) findViewById(R.id.etCityName);
        btnSave = (Button)findViewById(R.id.btnSave);
    }

    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        String selectedcity = arr.get(pos);
        Toast.makeText(this, "You clicked on position: "+selectedcity, Toast.LENGTH_SHORT).show();

        Intent i = new Intent(this, CityDetailActivity.class);
        i.putExtra("abcd",selectedcity);
        startActivity(i);
    }

    @Override    public void onClick(View view) {
        String name = etCityName.getText().toString();
        arr.add(name);
        aa.notifyDataSetChanged();
    }
}

Wednesday, August 1, 2018

Calculator

package net.samaysoftware.sampleproject12345;

import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnplus, btnminus, btnmult, btndiv, btneq, btndot;
    TextView tvScreen;
    Button[] arr= null;


    double num1;
    int op;

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

        findAllViews();
        arr = new Button[]{btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnplus, btnminus, btnmult, btndiv, btneq, btndot};
        for(int i = 0; i<arr.length;i++){
            arr[i].setOnClickListener(this);
        }

    }

    private void findAllViews() {
        btn0 = (Button) findViewById(R.id.btn0);
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);
        btn8 = (Button) findViewById(R.id.btn8);
        btn9 = (Button) findViewById(R.id.btn9);
        btndot = (Button) findViewById(R.id.btndot);
        btnplus = (Button) findViewById(R.id.btnplus);
        btnminus = (Button) findViewById(R.id.btnminus);
        btnmult = (Button) findViewById(R.id.btnmult);
        btndiv = (Button) findViewById(R.id.btndiv);
        btneq = (Button) findViewById(R.id.btneq);
        tvScreen = (TextView) findViewById(R.id.tvScreen);
    }

    @Override    public void onClick(View view) {
        Button clickedbutton = (Button) view;

        if(view== btn0 || view== btn1 || view== btn2 || view== btn3 || view== btn4 || view== btn5 || view== btn7 || view== btn6 || view== btn8 || view== btn9 || view== btndot ){
            String oldvalue = tvScreen.getText().toString();

            if(view==btndot && oldvalue.contains(".")){
                return;
            }
            String newvalue = oldvalue + clickedbutton.getText();
            tvScreen.setText(newvalue);

        }
        else if(view== btnplus || view== btnminus || view== btnmult || view== btndiv ){
            String oldvalue = tvScreen.getText().toString();
            num1 = Double.parseDouble(oldvalue);
            if(view==btnplus){
                op=1;
            }

            if(view==btnminus){
                op=2;
            }
            if(view==btnmult){
                op=3;
            }
            if(view==btndiv){
                op=4;
            }
            tvScreen.setText("");

        }
        else if(view == btneq){
            double num2 = Double.parseDouble(tvScreen.getText().toString());
            double ans = 0;
            switch (op){
                case 1:
                    ans = num1 + num2;
                    break;
                case 2:
                    ans = num1-num2;
                    break;
                case 3:
                    ans = num1 * num2;
                    break;
                case 4:
                    ans = num1 / num2;
                    break;
            }
            tvScreen.setText(ans+"");



        }
    }
}

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view