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.

AsyncTask Example Android with ProgressBar

MainActivity.java

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;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.TextView01);
		downloadPage();
	}

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

		@Override
		protected void onPreExecute() {
			//textView.setText("Hello !!!");
			progressBar = (ProgressBar) findViewById(R.id.progressBar1);
			progressBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);

		}

		@Override
		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(
							content));
					String s = "";
					while ((s = buffer.readLine()) != null) {
						response += s;
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			progressBar.setVisibility(View.INVISIBLE);
			textView.setText(result);
		}
	}

	private void downloadPage() {
		if (mTask != null
				&& mTask.getStatus() != DownloadWebPageTask.Status.FINISHED) {
			mTask.cancel(true);
		}
               // 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" });
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

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

	@Override
	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;
	}

}




activity_main.xml

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

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>



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

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


396LW NO topic_id




AD

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


1

Create TextView dynamically Android sample | create-textview-dinamically


Example source code for Android Developers

// clickable TextView
public TextView createTextView(String sText, Context con){
 TextView b = null;
 try {
  b = new TextView (con);
  b.setTextSize(15.0f);
  b.setTextColor(Color.rgb( 0, 0, 200));
  b.setOnClickListener(this);
  b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
  LayoutParams.WRAP_CONTENT));
  b.setText(sText);
  //tr.addView(b, 60,30);
  } catch (Exception e) {
  e.printStackTrace();
 return b;
 }
return b;
}
/*****************/
public void onClick(View view) {
 try {
  String s = ((TextView) view).getText().toString();
 }
 catch (Exception e1) {
   e1.printStackTrace();
 }
}
/***********/

// if you want restore in TextView after chagne of orientation
// you have to put  code to Manifest.xml android:configChanges

activity android:name=".main"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation" //this line important !!!!!!!

242

Cross Button in EditText Android | cross-button-in-edittext-android


Cross Button in EditText Android for deleting clearing text in EditText Example source code:
Example allow delete text in EditText by cross button, or do Button click performance.

main.xml type your package name and class
Put into drawable folder cross and ok image.

       <cz.okhelp.wiktionary.CustomEditText
            android:id="@+id/editTextZadejSlovo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:ems="10"
            android:hint="TypeAndPressGreen"
            android:singleLine="true"
            android:lines="1"
            android:maxLines="1" 
            android:drawableLeft="@drawable/cross"
            android:drawableRight="@drawable/ok" />
<!--button is invisible 0 height 0 width for performance click on button in EditText-->
        <Button
            android:id="@+id/btnGO"
            android:layout_width="0sp"
            android:layout_height="0sp"
            android:layout_weight="0"
            android:text="GO" />




CustomEditText.java

package cz.okhelp.wiktionary; // your package name

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.EditText;

public class CustomEditText extends EditText
{
  private Drawable dLeft,dRight;
  private Rect lBounds,rBounds;
  private static Button btnOk;

  public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }
  public CustomEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  public CustomEditText(Context context) {
    super(context);
  }

  @Override
  public void setCompoundDrawables(Drawable left, Drawable top,
      Drawable right, Drawable bottom)
  {
   if(left !=null) {
    	dLeft = left;
    }
   if(right !=null){
      dRight = right;
    } 
    
    super.setCompoundDrawables(left, top, right, bottom);
  }

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER) {
    	btnOk.requestFocus();
    	btnOk.performClick();

		}
		return super.onKeyUp(keyCode, event);
	}
  
  @Override
  public boolean onTouchEvent(MotionEvent event)
  {
  	final int x = (int)event.getX();
  	final int y = (int)event.getY();

  	if(event.getAction() == MotionEvent.ACTION_UP && dLeft!=null) {
  		lBounds = dLeft.getBounds();
  		
  		int n1 = this.getLeft();
  		int n2 = this.getLeft()+lBounds.width();
  		int n3 = this.getPaddingTop();
  		int n4 = this.getHeight()-this.getPaddingBottom();
  		// leva strana
  		if(    x>=(this.getLeft()) 
  				&& x<=(this.getLeft()+lBounds.width())
  				&& y>=this.getPaddingTop() 
  				&& y<=(this.getHeight()-this.getPaddingBottom()))
  		{
  			this.setText("");
  			event.setAction(MotionEvent.ACTION_CANCEL);//use this to prevent the keyboard from coming up
  		}
  	}
  	if(event.getAction() == MotionEvent.ACTION_UP && dRight!=null)
    {
      rBounds = dRight.getBounds();
      int n1 = this.getRight()-rBounds.width();
      int n2 = this.getRight()-this.getPaddingRight();
      int n3 = this.getPaddingTop();
      int n4 = this.getHeight()-this.getPaddingBottom();
      // prava strana
      if(x>=(this.getRight()-rBounds.width()) && x<=(this.getRight()-this.getPaddingRight())
      		&& y>=this.getPaddingTop() && y<=(this.getHeight()-this.getPaddingBottom()))
      {
      	btnOk.requestFocus();
      	btnOk.performClick();
      	event.setAction(MotionEvent.ACTION_CANCEL);//use this to prevent the keyboard from coming up
      }
    }
    
    return super.onTouchEvent(event);
  }

  @Override
  protected void finalize() throws Throwable
  {
    dRight = null;
    rBounds = null;
    super.finalize();
  }
	public void setBtnOk(Button btnOk) {
		this.btnOk = btnOk;
	}
	public Button getBtnOk() {
		return btnOk;
	}
}  



YourActivity.java

//onCreate
        Button  mBtnGO = (Button)findViewById(R.id.btnGO);
        CustomEditText mEditZadani = (CustomEditText)this.findViewById(R.id.editTextZadejSlovo);
        mEditZadani.setBtnOk(mBtnGO);
        mBtnGO.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
             // do stuff for signInButtonClick
          }
        });


//android.okhelp.cz/wiktionary-aplikace-pro-android/

android/wiktionary-0.png

123

R.java not generated - Android project in Eclipse issue | r-java-not-generating-android-project-in-eclipse-issue


If You create new xml file with prefix _ , for example _style.xml and You to clean project (Project->Clean), than package in folder project\gen will deleted with R.java class and new R.java not be created.

For to solving this problem You have to rename file without prefix _ as style.xml or name what You need and rebuild project.

If some ID cannot be resolved or is not a field get error occurence
You have to delete import android.R; in Activity.class if was inserted,
when this error is displayed.
80

List LinkedList add sort find Item in Java example | list-linkedlist-add-sort-find-item-in-java-example


List LinkedList Collections add sort find search Item, get searched item to string in Java example.

MainClass.java

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class MainClass {
	public static void main(String[] arg) {
		String[] arrayOfString = {"nothing", "Hello", "people"
				, "bye-bye", "hello", "world!", "End" };
		   
                   List<String> arrayList = new LinkedList<String>();
                  
                   for(String s: arrayOfString)
		     arrayList.add(s);

		    Collections.sort(arrayList);
		    // foreach
		    for (String str: arrayList)
		      System.out.println(str);
		    
		    Object objMin = Collections.min(arrayList);
		    System.out.println("Min is: " + objMin);
		    
		    Object objMax = Collections.max(arrayList);
		    System.out.println("Max is: " + objMax);
		    
		    int index = Collections.binarySearch(arrayList, "people");
		    System.out.println("Index of people is: " + index);
		    // print word on index 5
		    System.out.println("Index 5 is: " + arrayList.get(5));
                    String sItem = arrayList.get(5); // get item from index 5 to string
		    
		  }
}
/*
End
Hello
bye-bye
hello
nothing
people
world!
Min is: End
Max is: world!
Index of people is: 5
Index 5 is: people
*/
269

How to Add Home Screen Widgets on Your Android Phone | how-to-add-home-screen-widgets-on-your-android-phone


Long press by finger on screen
From dialogue select Widgets
Select your widget
Put your widget on the screen

Video tutorial - to add home screen widgets - Android 2.1