AsyncTask Example Android with ProgressBar
MainActivity.java
activity_main.xml
AndroidManifest.xml do not forget INTERNET uses-permission !!!!!!!
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)
Copy file to another
Copy and compress file
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "MyPicture.jpg");
// the Pictures directory exists?
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.flower_blue);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
Copy and compress file
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.flower_blue);
try {
FileOutputStream out = new FileOutputStream("new_bitmap.jpg");
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
Log.e("saveBitmap", e.getMessage());
}
Download image file from URL to ImageView Java Android source example code.
Context context = thisClass.this;
Drawable image = ImageOperations(context,
"//www.okhelp.cz/images/android/ad_4.png"
,"image.jpg");
ImageView imgView;
imgView = (ImageView)findViewById(R.id.idImageView);
imgView.setImageDrawable(image);
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
Android development example source code
Get supported language:
// import
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
// you have to add implementation
public class Main extends Activity implements TextToSpeech.OnInitListener {
private int _langTTSavailable = -1; // set up in onInit method
// declaration
private TextToSpeech mTts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// assigned handle - initialisation
mTts = new TextToSpeech(this,
(OnInitListener) this // TextToSpeech.OnInitListener
);
}
// Implements TextToSpeech.OnInitListener.
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
// Set preferred language to US english.
_langTTSavailable = mTts.setLanguage(Locale.US); // Locale.FRANCE etc.
if (_langTTSavailable == TextToSpeech.LANG_MISSING_DATA ||
_langTTSavailable == TextToSpeech.LANG_NOT_SUPPORTED) {
} else if ( _langTTSavailable >= 0) {
mTts.speak("Good morning",
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
} else {
// Initialization failed.
}
}
@Override
public void onDestroy() {
// TTS shutdown!
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
}
Get supported language:
private TextToSpeech mTts;
// public void onInit(int status){
int result;
String s;
result = mTts.setLanguage( Locale. CANADA ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " CANADA not supported<br>" ;}else{s+=" CANADA supported<br>";}
result = mTts.setLanguage( Locale. CANADA_FRENCH ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " CANADA_FRENCH not supported<br>" ;}else{s+=" CANADA_FRENCH supported<br>";}
result = mTts.setLanguage( Locale. CHINA ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " CHINA not supported<br>" ;}else{s+=" CHINA supported<br>";}
result = mTts.setLanguage( Locale. CHINESE ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " CHINESE not supported<br>" ;}else{s+=" CHINESE supported<br>";}
result = mTts.setLanguage( Locale. ENGLISH ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " ENGLISH not supported<br>" ;}else{s+=" ENGLISH supported<br>";}
result = mTts.setLanguage( Locale. FRANCE ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " FRANCE not supported<br>" ;}else{s+=" FRANCE supported<br>";}
result = mTts.setLanguage( Locale. FRENCH ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " FRENCH not supported<br>" ;}else{s+=" FRENCH supported<br>";}
result = mTts.setLanguage( Locale. GERMAN ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " GERMAN not supported<br>" ;}else{s+=" GERMAN supported<br>";}
result = mTts.setLanguage( Locale. GERMANY ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " GERMANY not supported<br>" ;}else{s+=" GERMANY supported<br>";}
result = mTts.setLanguage( Locale. ITALIAN ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " ITALIAN not supported<br>" ;}else{s+=" ITALIAN supported<br>";}
result = mTts.setLanguage( Locale. ITALY ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " ITALY not supported<br>" ;}else{s+=" ITALY supported<br>";}
result = mTts.setLanguage( Locale. JAPAN ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " JAPAN not supported<br>" ;}else{s+=" JAPAN supported<br>";}
result = mTts.setLanguage( Locale. JAPANESE ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " JAPANESE not supported<br>" ;}else{s+=" JAPANESE supported<br>";}
result = mTts.setLanguage( Locale. KOREA ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " KOREA not supported<br>" ;}else{s+=" KOREA supported<br>";}
result = mTts.setLanguage( Locale. KOREAN ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " KOREAN not supported<br>" ;}else{s+=" KOREAN supported<br>";}
result = mTts.setLanguage( Locale. PRC ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " PRC not supported<br>" ;}else{s+=" PRC supported<br>";}
result = mTts.setLanguage( Locale. ROOT ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " ROOT not supported<br>" ;}else{s+=" ROOT supported<br>";}
result = mTts.setLanguage( Locale. SIMPLIFIED_CHINESE ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " SIMPLIFIED_CHINESE not supported<br>" ;}else{s+=" SIMPLIFIED_CHINESE supported<br>";}
result = mTts.setLanguage( Locale. TAIWAN ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " TAIWAN not supported<br>" ;}else{s+=" TAIWAN supported<br>";}
result = mTts.setLanguage( Locale. TRADITIONAL_CHINESE ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " TRADITIONAL_CHINESE not supported<br>" ;}else{s+=" TRADITIONAL_CHINESE supported<br>";}
result = mTts.setLanguage( Locale. UK ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " UK not supported<br>" ;}else{s+=" UK supported<br>";}
result = mTts.setLanguage( Locale. US ); if (result == TextToSpeech.LANG_MISSING_DATA ||result == TextToSpeech.LANG_NOT_SUPPORTED) {s += " US not supported<br>" ;}else{s+=" US supported<br>";}
How to change the image dynamically in ImageView and button setOnClickListener Android sample.
Main.java
main.xml
Put into res/drawable this pictures:
Main.java
ipackage cz.okhelp.my_game;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Main extends Activity {
private ImageView hImageViewSemafor;
private Button hButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hImageViewSemafor = (ImageView)findViewById(R.id.idImageViewSemafor);
hButton = (Button) findViewById(R.id.idBtnChangeImage);
hButton.setOnClickListener(mButtonChangeImageListener);
}
View.OnClickListener mButtonChangeImageListener = new OnClickListener() {
public void onClick(View v) {
// setImageResource will change image in ImageView
hImageViewSemafor.setImageResource(R.drawable.semafor_green);
}
};
}
main.xml
Put into res/drawable this pictures:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:src="@drawable/semafor_red"
android:id="@+id/idImageViewSemafor"
android:background="#66FFFFFF"
android:adjustViewBounds="true"
android:maxWidth="47dip"
android:maxHeight="91dip"
android:padding="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
How add pair of strings to Hashtable, how get pair key value from Hashtable, how split string, basic Java Android example.
MainClass.java
MainClass.java
import java.util.Enumeration;
import java.util.Hashtable;
public class MainClass {
public static void main(String[] arg) {
// english;germany dictionary
String[] arrayOfString = { "one;eine", "two;zwei", "three;drei" };
Hashtable<String, String> hashTable = new Hashtable<String, String>();
for(String s: arrayOfString){
String[] array = s.split(";");
String sKey ="", sValue="";
if(array.length > 1){
sKey = array[0]; sValue = array[1];
hashTable.put(sKey, sValue);
}
}
Enumeration<String> enumer = hashTable.keys();
while (enumer.hasMoreElements()) {
String keyFromTable = (String) enumer.nextElement();
// get Returns the value to which the specified key is mapped,
// or null if this map contains no mapping for the key
System.out.println(keyFromTable + " = " + hashTable.get(keyFromTable));
}
}
}
/*
two = zwei
one = eine
three = drei
*/
Editace: 2012-12-27 15:30:36
Počet článků v kategorii: 396
Url:asynctask-example-android-with-progressbar