ip: 3.129.216.15 DKs blog - Android examples

DK's Blog

Android examples

Usage of broadcast in Android applicaion

 

Receive class:

public class Favorites extends ListActivity {
 
    SomeReceiver r;
    IntentFilter f;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);
        //.... some code

        //register receiver 
        f = new IntentFilter("hr.globaldizajn.android.SHUTDOWN");
        r = new SomeReceiver();
        registerReceiver(r, f);
    }

    //....

    public class SomeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("logiranje:SomeReceiver","extra filterName: " + intent.getStringExtra("filterName"));
            // do what you like here
	}

    }
}

 

Broadcast class:

//Some other activity in galaxy far far away ...
    Context c = activity.this; //need activity to fire broadcast!

    Intent i = new Intent("hr.globaldizajn.android.SHUTDOWN");
    i.putExtra("filterName", "some message or useful data");
    c.sendBroadcast(i);

Create custom ListActivity

 

public class MyActivity extends ListActivity

{
    static public ArrayList> MyList = new ArrayList>(); 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] names = new String[listEkran1.size()];
        for (int i=0;i<10;i++){
            HashMap row = new HashMap(); //create HashMap
            row.put("Line1","" + i); //fill it with stupid data
            row.put("Line2","" + i);
            MyList.add(row); //add it to array
        }
        this.setListAdapter(new MyArrayAdapter(this, names, Mylist, 0));
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Strint s1;
        s1  = "You selected position: " + position + " Line1: " + MyList.get(position).get("List1");
        s1 += "You selected position: " + position + " Line2: " + MyList.get(position).get("List2");
        Toast.makeText(this, s1, Toast.LENGTH_SHORT).show();
    }
}


public class MyArrayAdapter extends ArrayAdapter {
    private final ArrayList> list;
    private final Activity context;

    //constructor
    public MyArrayAdapter(Activity c, String[] names, ArrayList> _lists) {
        super(context, R.layout.listRow, names);
        this.context = c;
        lists = _lists;
    }

    //this will be executed for every item in listbox so you can do whatever you like
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
	LayoutInflater inflater = context.getLayoutInflater();
	View rowView = inflater.inflate(R.layout.listRow, null, true);

        TextView label = (TextView) rowView.findViewById(R.id.label);
        label.setText(lists.get(position).get("Line1"));
        TextView label2 = (TextView) rowView.findViewById(R.id.label2);
        if ((position%2)==0)
            label2.setTextColor(context.getResources().getColor(R.color.red));
        Log.i("MyArrayAdapter:getView","position: " + position); //display Log in eclipse
        return rowView;
    }

}

 

listRow.xml

< ? xml version="1.0" encoding="utf-8" ? >

< AbsoluteLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"
>
        android:id="@+id/label"
        android:text="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16px"
        android:textStyle="bold"
        android:layout_x="1px"
        android:layout_y="1px"
        android:textColor="#aaffaa"/>
   
        android:id="@+id/label2"
        android:textSize="13px"
        android:textStyle="italic"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_x="1px"
        android:layout_y="30px"

/>

 


Example of thread which can be stopped and started from another thread

 

Runnable r= new Runnable() {
    public void run() {
        // some code
         ...
        wait();
	try {

            wait();
	} catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
	}

	if (!Thread.currentThread().isInterrupted()) { // Alert user of success. 
            Log.d("tag","interupted");
        }
    }
    t=new Thread(r); 
    t.start(); 


    //from thread/activity far far away ... 
    //restart thread 
    t.interrupt();

 


Example of iisting all files and subdirectories from directory

File folder = new File(ime);
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    Log.d("tag","filename: " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    Log.d("tag","directory: " + listOfFiles[i].getName());
  }
}

 


Listing only subdirectories in android (example)

 

File dir = new File(".");
FileFilter filter = new FileFilter() {
	public boolean accept(File file) {
		return file.isDirectory();
	}
};

File[] file = dir.listFiles(filter);
for (int i = 0; i < file.length; i++) {
	Log.d("tag","directoryname: " + file[i].getName());
}

 


Example of starting the new thread in android (java)

new Thread() {
    public void run () {
  }
}.start();

 


How to disable back button in android application (example)

@Override
public void onBackPressed() {
   return;
}

 


How to convert string to integer (example)

int num  = Integer.parseInt("12");
int num2 = Integer.getInteger(et.getText().toString(),0);

 


How to convert date which is in string format to another, string to string date conversion

 

try {  
      String str_date="11-03-2007"; //this is string which needs converting
      
      DateFormat formatterIn,formatterOut; 
      formatterIn = new SimpleDateFormat("MM-dd-yyyy"); //Input date format (string)
      formatterOut = new SimpleDateFormat("dd-MM-yyyy"); //Output date format (string)
      Date date = new Date(); 

      date = (Date)formatterIn.parse(str_date); //convert str->date
      StringBuilder Out = new StringBuilder( formatterOut.format(date) ); //convert date->str  
 
      System.out.println("converted date " + Out );
      
} catch (ParseException e) {
      System.out.println("Exception :"+e);
}

 


How to move to another EditText from keyboard, without removing keyboard (back button) ned choosing another EditText.

I use LinearLayout and single line Edit, then enter key is replaced with key to move to next EditText.
Add this to .xml file inside EditText

 

android:singleLine="true"

android:nextFocusDown="@+id/myNextEditText"

 


@2016