Okhelp.cz

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.

Android Samples












AbsListView
AbstractAccountAuthenticator
AbstractThreadedSyncAdapter
AccelerateInterpolator
AccessibilityEvent
AccessibilityService
AccessibilityServiceInfo
Account
AccountAuthenticatorActivity
AccountAuthenticatorResponse
AccountManager
Activity
ActivityInfo
ActivityInstrumentationTestCase2
ActivityManager
ActivityUnitTestCase
AdapterContextMenuInfo
AdapterView
AlarmManager
AlertDialog
AlphaAnimation
AndroidTestCase
Animation
AnimationSet
AnimationUtils
Application
ApplicationTestCase
AppWidgetManager
AppWidgetProvider
ArrayAdapter
AssetFileDescriptor
AsyncTask
AttributeSet
AudioManager
AuthenticatorDescription
AuthenticatorException
AutoCompleteTextView
BackupAgent
BackupAgentHelper
BackupDataInput
BackupDataOutput
BackupManager
BaseAdapter
BaseColumns
BaseExpandableListAdapter
Binder
Bitmap
BitmapDrawable
BitmapFactory
BitmapShader
BluetoothAdapter
BluetoothDevice
BluetoothServerSocket
BluetoothSocket
BroadcastReceiver
Build
Bundle
Button
Callback
Camera
CameraInfo
Canvas
Color
ColorFilter
CompletionInfo
ComponentName
CompoundButton
ConditionVariable
Config
ConfigurationInfo
Contacts
ContactsContract
ContentProvider
ContentProviderClient
ContentProviderOperation
ContentResolver
ContentUris
ContentValues
Context
ContextMenu
ContextMenuInfo
Cursor
CursorAdapter
Data
DatePicker
DatePickerDialog
DecelerateInterpolator
DeviceAdminReceiver
DevicePolicyManager
Dialog
DialogInterface
Display
DisplayMetrics
Drawable
Editable
EditorInfo
EditText
EditTextPreference
Email
Environment
Equalizer
ETC1Util
ExpandableListActivity
ExpandableListAdapter
ExpandableListContextMenuInfo
ExpandableListView
FileBackupHelper
FillType
Filterable
FloatMath
FocusFinder
FormatException
Gallery
Gesture
GestureDetector
GestureLibraries
GestureLibrary
GestureOverlayView
GLES10
GLES20
GLSurfaceView
GLU
GLUtils
Gravity
GridView
Handler
HandlerThread
Html
CharArrayBuffer
CheckBox
CheckBoxPreference
Chronometer
IBinder
Im
ImageButton
ImageSwitcher
ImageView
InputConnection
InputMethodManager
InputMethodService
Instrumentation
Intent
IntentFilter
JetPlayer
Key
Keyboard
KeyboardView
KeyEvent
KeyCharacterMap
LayoutAnimationController
LayoutInflater
LayoutParams
LinearLayout
LinkMovementMethod
ListActivity

ListAdapter
ListPreference
ListView
LiveFolders
Log
Looper
Matrix
MediaController
MediaPlayer
MediaScannerConnection
MediumTest
Menu
MenuInflater
MenuItem
Message
Messenger
MetaKeyKeyListener
MoreAsserts
MotionEvent
MovementMethod
MultiAutoCompleteTextView
NameNotFoundException
NdefMessage
NdefRecord
NfcAdapter
Notification
NotificationManager
OnAccountsUpdateListener
OnBufferingUpdateListener
OnClickListener
OnCompletionListener
OnCheckedChangeListener
OnInitListener
OnItemClickListener
OnItemSelectedListener
OnJetEventListener
OnKeyListener
OnPreparedListener
OnScrollListener
OnSharedPreferenceChangeListener
OnTouchListener
OnVideoSizeChangedListener
OperationApplicationException
OperationCanceledException
Options
PackageInfo
PackageManager
Paint
PaintDrawable
PaintFlagsDrawFilter
Parcel
Parcelable
ParcelFileDescriptor
Path
PendingIntent
People
Phone
Phones
Picture
PictureDrawable
PixelFormat
PorterDuff
PorterDuffXfermode
PowerManager
Preference
PreferenceActivity
PreferenceCategory
PreferenceManager
PreferenceScreen
Process
ProgressBar
ProgressDialog
QuickContactBadge
RadioButton
RadioGroup
RatingBar
RawContacts
RecognitionService
RecognizerIntent
Rect
RectF
RelativeLayout
RemoteCallbackList
RemoteException
RemoteViews
ResolveInfo
ResourceCursorAdapter
Resources
Row
ScaleGestureDetector
ScrollingMovementMethod
ScrollView
SearchManager
SearchRecentSuggestions
SearchRecentSuggestionsProvider
SeekBar
Sensor
SensorEvent
SensorEventListener
SensorManager
Service
ServiceConnection
ServiceTestCase
Shader
ShapeDrawable
SharedPreferences
SimpleAdapter
SimpleCursorAdapter
SimpleCursorTreeAdapter
SimpleExpandableListAdapter
Size
SmallTest
SmsManager
SmsMessage
SpannableString
Spanned
SparseArray
SpeechRecognizer
Spinner
SpinnerAdapter
SQLException
SQLiteDatabase
SQLiteOpenHelper
SQLiteQueryBuilder
StatusUpdates
StructuredName
Style
StyleSpan
Surface
SurfaceHolder
SurfaceView
SyncResult
SystemClock
TabActivity
TabHost
TableLayout
TableRow
TabSpec
TestSuiteBuilder
TextSwitcher
TextToSpeech
TextUtils
TextView
TextWatcher
Time
TimePicker
TimePickerDialog
Toast
ToggleButton
Transformation
TranslateAnimation
TypedArray
Typeface
UiThreadTest
Uri
UriMatcher
URLSpan
Vibrator
VideoView
View
ViewFlipper
ViewGroup
ViewParent
ViewSwitcher
Visualizer
WakeLock
WallpaperManager
WallpaperService
WebView
Window
WindowManager
Xfermode
Xml
XmlResourceParser


397LW NO topic_id



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


127

Force Screen On - dont use WakeLock - use getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - Android sample | force-screen-on-dont-use-wakelock-use-getwindow-addflagswindowmanager-layoutparams-flag_keep_screen_on-android-sample


FLAG_KEEP_SCREEN_ON saving energy. Protects the battery if a user closing applications using the Return button on device. The device will returned to user screen mode settings.

@Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        //..........
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
131

Draw color line set stroke width Android basic example | draw-line-android-basic-example


Canvas, drawLine(), setStrokeWidth(), Paint, setAntiAlias(boolean), onDraw()

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new SampleView(this));
	}

	private static class SampleView extends View {

		// CONSTRUCTOR
		public SampleView(Context context) {
			super(context);
			setFocusable(true);

		}

		@Override
		protected void onDraw(Canvas canvas) {

			canvas.drawColor(Color.YELLOW);
			Paint p = new Paint();
			// smooths
			p.setAntiAlias(true);
			p.setColor(Color.RED);
			p.setStrokeWidth(4.5f);
			// opacity
			p.setAlpha(0x80); //
			// drawLine (float startX, float startY, float stopX, float stopY,
			// Paint paint)
			canvas.drawLine(0, 0, 40, 40, p);
			canvas.drawLine(40, 0, 0, 40, p);

		}

	}
}
377

3. Fragments Tutorial HeadlinesFragment – Czech language | 3-fragments-tutorial-headlinesfragment-czech-language


Dil 3. HeadlinesFragment.java
V 1. dílu jsme se něco dozvěděli od XML souborech
V 2. dílu jsme rozebrali MainActivity.java


V tomto dílu si rozebereme záludnosti v HeadlinesFragment.java souboru.
Používáme příklad i zip porojekt z https://developer.android.com/training/basics/fragments/creating.html Pozorně si jej nastudujte.

package com.example.android.fragments;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
// pokud chceme aby byla aplikace spustitelná i v nižších verzích Androidu
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

// extends ListFragment důležité pro základní obsluhu ListView atd.
public class HeadlinesFragment extends ListFragment {
	// zajistí zpětné odesílání zprav - zde zachytí kliknutí uživatele na položku
        // v ListView - seznamu položek 
    OnHeadlineSelectedListener mCallback;

    // pro odposlouchávání zpráv v ListView a odesílání do MainActivity.java
    public interface OnHeadlineSelectedListener {
        /**
		funkce je volána onArticleSelected z HeadlinesFragment když uživatel
                klikne na item v ListView - položku seznamu -
		Tělo funkce je v MainActivity!!! Tam proběhnou potřebné úkony.
                Například výměna fragmentů atd. */
        public void onArticleSelected(int position);
    }

	/** Protože je HeadlinesFragment rozšířením (extends) ListFragment
	používá funkci onCreate(). 
        ArticleFragment extends Fragment bude používat onCreateView() 
	*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        
		// Zde si pohlídáme verze Androidu a přiřadíme jim 
                // předdefinovanou šablonu XML souboru
		// Je to důležité pokud chceme využívat více možností, 
                // které nové verze nabízejí 
		// například podbarvení vybrané položky seznamu
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

		
		// zde se vytovoří jednotlivé položky seznamu v ListView
		// Pole vypadá takto:  
		// static String[] Headlines = {"Article One","Article Two"};
		// položky tedy ponesou názvy ze String[] Headlines
		// Teoreticky si menší pole položek můžete dát i sem pro jednodušší editaci
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

		
		// Pokud se bude zobrazovat dual-panel 
                // (pro tablety, větší obrazovky) 
                // například je dobré
		// když bude zvýrazněna vybraná položka setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		// Toto provádíme v onStart(), kdy máme přístup k listview
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

	// onAttach() bude asi deprecated, tak můžete vyzkoušet
	/* 
			@Override
		public void onAttach(Context context) {
			super.onAttach(context);

			Activity a;

			if (context instanceof Activity){
				a=(Activity) context;
			}
		}
	*/
// nebo pohledat něco na inetu 
	
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

		
		// Zde přiřadíme odposlouchávání zprávy kliknutí na položku ListView 
		// a zpětnou vazbu s MainActivity.
		// Pokud se to nepodaří, bude zaznamenáno a předáno dál chybové hlášení
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    /** kliknuto na položku ListView */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
                // long id se bude hodit například při obsluze sql.databází
        
		// Upozorní - předá zprávu MainActivity.java, že uživatel 
		// klikl na položku a odešle i pozici v seznamu
                mCallback.onArticleSelected(position);
        
        
		// getListView().setItemChecked(position, true); 
		// má zajistit podbarvení 
		// - zvýraznění vybrané položky,
		// ale mi to nefungovalo, tak jsem ještě znovu přidal,
		// které je už v onStart() a už to funguje jak má
		// Možná nějaká záludnost v mém telefonu :(
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		 
        getListView().setItemChecked(position, true);
    }
}
295

Java Basic Rules | java-basic-rules



// file name MyFirstClass.java

import java.util.*;
import java.lang.Math;
import java.io.*;
import javax.swing.*;

public class MyFirstClass{ // start of program
  public static void main(String[] args) { // basic  function main

// variables and calculation
int a=2;
int b=3;
int c=Integer.parseInt(JOptionPane.showInputDialog(" Put number: ", "1"));
System.out.println("Number is: "+c);
System.out.println(a+" * "+b+" = "+(a*b));
System.out.println("a^3 "+Math.pow(a,b));

//array
int[] array_my=new int[10];
array_my[0]=3;
array_my[1]=5;
System.out.println("Number of elements "+array_my.length+" 1 + 2 element of array "+(array_my[0]+array_my[1]));

//strings
String txt="Quick red fox";
String txt2=JOptionPane.showInputDialog("Write text: ", "word");
System.out.println("Text is: "+txt2);
String[] count_of_word=txt.split(" ");
System.out.println("Length: "+txt.length()+" Count of words "+count_of_word.length);
System.out.println(txt +" -> "+txt.replace("red","brown"));
System.out.println("First 5 chars of string is: "+ txt.substring(0,5));

//for a if
for(int i=0; i<10;i++){
	if(i==3)System.out.println("i equal "+i);
	}

// file
try {
  File soubor=new File("some_file.txt");
  if(!soubor.exists()){
	System.out.println("File dont exist");
  }
  else { // utf-8 encoding
    BufferedReader in1 = new BufferedReader(new InputStreamReader(new FileInputStream(soubor),"UTF-8"));
    BufferedWriter out1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("zapis.txt"),"UTF-8"));
    String str;
      while ((str = in1.readLine())!=null){
        System.out.println(str);
        out1.write(str+"

"); } in1.close(); out1.close(); } } catch(IOException e){System.out.println("Error " + e);} // dir File pathName = new File("some_dir"); String[] fileNames = pathName.list(); if(pathName.exists()) System.out.println("Name of first file in \"some_dir\": "+fileNames[0]); else System.out.println("dir not exist"); //function int nResult = calculateMyFc(3,5); System.out.println("Result of function: "+nResult); } // end of function main // new function , you can add to end MyFc = my function public static int calculateMyFc(int a, int b){ return (a+b); } } // end of class of program
49

Emulator window was out of view and was recentred - Android emulator warning | emulator-window-was-out-of-view-and-was-recentred-android-emulator-warning


Emulator window was out of view and was recentred
Emulator] WARNING: Data partition already in use. Changes will not persist!
Emulator] WARNING: SD Card image already in use: C:\Documents and Settings\user_name\.android\avd\hvga21_up1_7.avd/sdcard.img
Emulator] WARNING: Cache partition already in use. Changes will not persist!

Basic step
Try restart Eclipse if using from menu File->Restart

Other solutions

Solution 1: try restart ADB server
//android.okhelp.cz/how-quickly-restart-adb-exe-adb-server-android-emulator-example/


Solution 2:

Delete Run Configuration


//android.okhelp.cz/android-emulator-wont-run-application-started-from-eclipse/





Solution 3:
Try delete:

c:\Documents and Settings\user_name\.android\avd\my_avd.avd\cache.img
c:\Documents and Settings\user_name\.android\avd\my_avd.avd\userdata-qemu.img



Try solution 4:
Eclipse menu select Window->Preferences->Android

Windows 32

FROM: C:\Program Files\Android\android-sdk
TO: C:\PROGRA~1\Android\android-sdk

Windows 64

FROM: C:\Program Files (x86)\Android\android-sdk
TO: C:\PROGRA~2\Android\android-sdk


Editace Jana Žákovská : 2012-01-25 14:51:12
Počet článků v kategorii: 397
Url:android-samples
Share
Share
Tweet