Recepty, články, nápady, programování. Dříve dum-zahrada, finance, internet a know-how.okhelp.cz Pro lepší výsledky hledání používejte i diakritiku.

AsyncTask Example Android with ProgressBar



package com.asynctaskexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView textView;
	private ProgressBar progressBar;
	private DownloadWebPageTask mTask = null;

	protected void onCreate(Bundle savedInstanceState) {
		textView = (TextView) findViewById(R.id.TextView01);

	// AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .
	private class DownloadWebPageTask extends AsyncTask<String, Integer, String> {

		protected void onPreExecute() {
			//textView.setText("Hello !!!");
			progressBar = (ProgressBar) findViewById(R.id.progressBar1);

		protected void onProgressUpdate(Integer... values) {


		protected String doInBackground(String... urls) {
			String response = "";
			for (String url : urls) {
				DefaultHttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);
				try {
					HttpResponse execute = client.execute(httpGet);
					InputStream content = execute.getEntity().getContent();

					BufferedReader buffer = new BufferedReader(new InputStreamReader(
					String s = "";
					while ((s = buffer.readLine()) != null) {
						response += s;

				} catch (Exception e) {
			return response;

		protected void onPostExecute(String result) {

	private void downloadPage() {
		if (mTask != null
				&& mTask.getStatus() != DownloadWebPageTask.Status.FINISHED) {
               // execute(String[]) you can put array of links to web pages, or array of Integer[] 
               // if first param is Integer[] etc.
		mTask = (DownloadWebPageTask) new DownloadWebPageTask()
				.execute(new String[] { "//android.okhelp.cz/android-market.html",
						"//android.okhelp.cz/android-market.html" });

	protected void onDestroy() {

		if (mTask != null
				&& mTask.getStatus() != DownloadWebPageTask.Status.FINISHED) {
			mTask = null;

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;



<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:layout_height="wrap_content" />

        android:text="@string/hello_world" />


AndroidManifest.xml do not forget INTERNET uses-permission !!!!!!!

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

397LW NO topic_id


Další témata ....(Topics)


Display screen size resolution density dimension Android | display-screen-dimension

Get display, screen resolution - dimension Android phone development example source code.

 Display display = getWindowManager().getDefaultDisplay();
int nWidth = display.getWidth();
int nHeight = display.getHeight();

          DisplayMetrics metrics = new DisplayMetrics();
            //get density per inch for example: 120 , 160 , 240
            mXDpi = metrics.xdpi; // 160 The exact physical pixels per inch of the screen in the X dimension. 
            mYDpi = metrics.ydpi;

// density
int nDensity = metrics.densityDpi; // 160 screen density expressed as dots-per-inch

          float  mMetersToPixelsX = mXDpi / 0.0254f; // 1 inch == 0.0254 metre
          float  mMetersToPixelsY = mYDpi / 0.0254f;
// Resolution
// The total number of physical pixels on a screen.
int wPix = metrics.widthPixels; // 320 The absolute width of the display in pixels.
int hPix = metrics.heightPixels; // 480 The absolute height of the display in pixels.
int nWidthDisplay = (wPix < hPix)? wPix : hPix;

float nWidthScreenInInch = wPix / mXDpi; //320 / 160 == 2.0 in inch.
float nHeightScreenInInch = hPix / mYDpi; //480 / 160 == 3.0 in inch.

// for example:
// density 120 per inch
//width 320 pix / 120 dpi == width 2.66 inch
//height 480 pix / 120 dpi == height 4.0 inch 

// density 240 per inch
//width 320 pix / 240 dpi == width 1.33 inch
//height 480 pix / 240 dpi == height 2.0 inch 

HTC Desire HD
11 (4.3) Diagonal cm (in)
480×800 Resolution
85 (217) ppcm (PPI - Pixels per inch)

480 / 217 = 2.21 inch
800 / 217 = 3.69 inch
Math.sqrt( 2.21*2.21 + 3.69 * 3.69) = 4.3 inch - diagonal


Typical screen widths:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Emulator skins in the Android SDK

Low density (120), ldpi

Medium density (160), mdpi

High density (240), hdpi

Extra high density (320), xhdpi

Small screen
QVGA (240x320) 480x640

Normal screen
WQVGA400 (240x400)

WQVGA432 (240x432)
HVGA (320x480) WVGA800 (480x800)

WVGA854 (480x854)


Large screen
WVGA800** (480x800)

WVGA854** (480x854)
WVGA800* (480x800)

WVGA854* (480x854)


Extra Large screen
1024x600 WXGA (1280x800)



* To emulate this configuration, specify a
custom density of 160 when creating an AVD that uses a WVGA800 or WVGA854 skin.

** To emulate this configuration, specify a custom density of 120 when creating an AVD that
uses a WVGA800 or WVGA854 skin.

† This skin is available with the Android 3.0 platform

Every fragment must have an empty constructor Android Java Class | every-fragment-must-have-an-empty-constructor-android-java-class

You have to add constructor!

    public static class YourFragment extends Fragment {
    //you have to add constructor!!!!!	
    public YourFragment(){}

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.activity_main, container, false);

            return view;



Android studio list of useful shortcuts or like Eclipse | android-studio-list-of-useful-shortcuts

File -> Settings -> Keymap you can do select Eclipse keymap from drop down menu

Ctrl+Shift+A (Help | Find Action on the main menu) and start typing the name of the action. Choose the desired action from the suggestion list.

Ctrl+Click (on Windows) or Cmd+Click (on MacOS) a tab in the editor to navigate to any part of the file path. Select the necessary element in the drop-down, and the corresponding file path opens in an external browser (e.g., in the Explorer, if your OS is Windows).


Find - Rename

Ctrl+F find

Refactor | Rename: Shift+F6  ( +F6)

Find and replace: CTRL + R

Go to variable declaration: CTRL + B

Ctrl+Shift+I (View | Quick Definition)

Ctrl+Alt+F7  (Edit | Find | Show Usages in the main menu)

Ctrl+Shift+F find in project

Ctrl+Shift+F7 (Edit | Find | Highlight Usages in File) to quickly highlight usages of some variable in the current file.
Use F3 and Shift+F3 keys to navigate through highlighted usages.
Press Escape to remove highlighting.

Ctrl+W (extend selection) in the editor selects the word at the caret and then selects expanding areas of the source code. For example, it may select a method name, then the expression that calls this method, then the whole statement, then the containing block, etc. You can also select the word at the caret and the expanding areas of the source code by double-clicking the target areas in the editor.

To search through the classes, files, tool windows, actions, settings, and symbols of your project by double pressing the Shift key

Ctrl+P (View | Parameter Info) e.g. localURL = new URL(localUrlString); select localUrlString and press Ctrl + P

Show html documentation tooltips:  CTRL + Q



Comment uncomment single line: CTRL + /

Comment uncomment selected text: CTRL + SHIFT + /

Code completion (Ctrl+Space)

Alt key and mouse pointer dragging for column selection

If nothing is selected in the editor, and you press Ctrl+C, then the whole line at caret is copied to the clipboard.

Ctrl + Delete  delete word from caret to end.

Ctrl + Backspace delete word from caret to start.

Duplicate line: CTRL + D

To compare two directories,or  jar files, select one or both of them in the Project view and press Ctrl+D.

Editor Delete Line: CTRL + Y

Move line UP, DOWN. Select a code fragment and press Ctrl+Shift+Up or Ctrl+Shift+Down.

To open any class or file in the editor at the desired line, press Ctrl+Shift+N (Navigate | File), start typing the name, and choose the one from the suggestion list. Then type the colon (:) and a line number

Ctrl+Shift+Enter to complete a current statement such as if, do-while, try-catch, return (or a method call)

Alt+Enter to invoke a quick fix or intention action, press the right arrow key to reveal the list of additional options.

To quickly review your recent changes to the project: Alt+Shift+C

Code Completion, you can accept the currently highlighted selection in the popup list with the period character (.), comma (,), semicolon (;), space and other characters.

Quickly move between methods in the editor:  Alt+Up and Alt+Down

Ctrl+Shift+J shortcut joins two lines into one and removes unnecessary space to match your code style

Ctrl+Shift+V to choose and insert recent clipboard contents into the text

Inheritance hierarchy for a selected class: Ctrl+H

Right-clicking on a breakpoint marker  you can quickly enable/disable the breakpoint or adjust its properties.

Evaluate the value of any expression while debugging the program, select its text in the editor (you may press a Ctrl+W a few times to efficiently perform this operation) and press Alt+F8.

Quickly evaluate the value of any expression while debugging the program, hold Alt and click this expression to see its value and calculate it, call a method, etc.

You can use the Extract Variable refactoring even on incomplete statements. Just select the necessary block in the editor and press Ctrl+Alt+V.

To open any particular method or field in editor: Ctrl+Alt+Shift+N

Add unimplemented methods: CTRL + I

Override methods: CTRL + O

Format code: CTRL + ALT + L

Show project: ALT + 1

Show logcat: ALT + 6

Hide project - logcat: SHIFT + ESC

Build: CTRL + F9

Build and Run: CTRL + F10

Alt+Shift+F10  access the Run/Debug dropdown on the main toolbar

Collapse all: CTRL + SHIFT + NumPad +

Expand all: CTRL + SHIFT + NumPad -

HorizontalScrollView ScrollView horizontal vertical Android xml example | horizontalscrollview-scrollview-horizontal-vertical-android-xml-example

HorizontalScrollView ScrollView LinearLayout horizontal vertical Android xml basic example and image.

[caption id="attachment_889" align="alignleft" width="200" caption="horizontal scrollview horizontalscrollview android"]horizontalscrollview-android[/caption]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:layout_width="fill_parent" android:layout_height="fill_parent"

	// horizontal and vertical Scrollview
	<ScrollView android:id="@+id/ScrollView01"
		android:layout_height="135px" android:layout_width="wrap_content"

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

			<LinearLayout android:id="@+id/LinearLayout02"
				android:layout_width="wrap_content" android:orientation="vertical"
				<LinearLayout android:orientation="horizontal"
					android:layout_width="fill_parent" android:layout_height="fill_parent"
					<TextView android:text="red" android:gravity="center_horizontal"
						android:background="#aa0000" android:layout_width="200px"
						android:layout_height="fill_parent" android:layout_weight="1" />
					<TextView android:text="green" android:gravity="center_horizontal"
						android:background="#00aa00" android:layout_width="200px"
						android:layout_height="fill_parent" android:layout_weight="1" />
					<TextView android:text="blue" android:gravity="center_horizontal"
						android:background="#0000aa" android:layout_width="200px"
						android:layout_height="fill_parent" android:layout_weight="1" />
					<TextView android:text="yellow" android:gravity="center_horizontal"
						android:background="#aaaa00" android:layout_width="200px"
						android:layout_height="fill_parent" android:layout_weight="1" />

				<LinearLayout android:orientation="vertical"
					android:layout_width="fill_parent" android:layout_height="fill_parent"
					<TextView android:text="row one" android:textSize="15pt"
						android:layout_width="fill_parent" android:layout_height="wrap_content"
						android:layout_weight="1" />
					<TextView android:text="row two" android:textSize="15pt"
						android:layout_width="fill_parent" android:layout_height="wrap_content"
						android:layout_weight="1" />
					<TextView android:text="row three" android:textSize="15pt"
						android:layout_width="fill_parent" android:layout_height="wrap_content"
						android:layout_weight="1" />
					<TextView android:text="row four" android:textSize="15pt"
						android:layout_width="fill_parent" android:layout_height="wrap_content"
						android:layout_weight="1" />


Other sample

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:layout_height="wrap_content" >

            android:orientation="horizontal" >
            android:text="Hello world! First TextView" />

            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />





Android Studio failed to convert drawable into a drawable | android-studio-failed-to-convert-drawable-into-a-drawable

Try this:
- check names of drawables (file name must contain only abc...xyz 012...789 _ . in Resources folder ,
names have to start with lower case
MyImage.jpg == problem ,
names with space
my image.jpg == problem,
names with -
my-image.png == problem)
- check duplicate names with other extension ( my_image.jpg - my_image.png makes the problem)
- restart Android Studio
- if problem persist:
- check c:\Users\me\AndroidStudioProjects\myProject\myModule\build\intermediates\res\merged\debug\ drawable folder for corupted names or delete ALL drawable folders
- synk projekt, rebuild projekt
- if problem persist:
- restart Android Studio, wait for complete closure of the Android Studio!

Editace: 2012-12-27 15:30:36
Počet článků v kategorii: 397

11 Share