Archive for the ‘ Android ’ Category

nullpointerexception non activity class hatası ile karşılaştığınızda aşağıdaki şekıilde çözebilirsiniz.
Android içinde normal bir Java(Non-Activity and Non-View) sınıfından herhangi bir Activity çağırmak istediğimizde aşağıdaki gibi iki şekilde çağırabiliriz.

1. Context göndereceğimiz sınıfın yapıcısında this ile göndermektir.

MyMainActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class MyMainActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MyTestClass myTestClass=new MyTestClass(this);
        myTestClass.startSecondActivity();
    }
}

MyTestClass.java

import android.content.Context;
import android.content.Intent;

public class MyTestClass {

	Context context;

	public MyTestClass(Context context) {
		super();
		this.context = context;
	}
	public void startSecondActivity()
	{
		Intent intent=new Intent(context, SecondActivity.class);
		context.startActivity(intent);
	}
	
}

SecondActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class SecondActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Toast.makeText(getApplicationContext(), "Second activity", Toast.LENGTH_LONG).show();
	}

}

2. yol ise intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); şeklinde SecondActivity i yeni bir task ile başlatmaktır. Bu şekilde yeni task ile başlattığımız da hem MyTestClass myTestClass=new MyTestClass(this); hem de MyTestClass myTestClass=new MyTestClass(getApplicationContext()); start edebiliyoruz.

MyMainActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class MyMainActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MyTestClass myTestClass=new MyTestClass(getApplicationContext());
        myTestClass.startSecondActivity();
    }
}

MyTestClass.java

import android.content.Context;
import android.content.Intent;

public class MyTestClass {

	Context context;

	public MyTestClass(Context context) {
		super();
		this.context = context;
	}
	public void startSecondActivity()
	{
		Intent intent=new Intent(context, SecondActivity.class);
//Yeni task ile başlattık.
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
}

SecondActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class SecondActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Toast.makeText(getApplicationContext(), "Second activity", Toast.LENGTH_LONG).show();
	}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.call"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".MyMainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="SecondActivity"></activity>
    </application>

</manifest>

Download CallActivity.zip source code

Android ile KSOAP2 kullanarak SOAP Web Serviceden data çekmeye çalışırken karşılaştığım sorunu çözdükten sonra paylaşmaya çalıştım. En önemli sorun When Parsing the Soap response problem Android Developer grubuna sorulan sorudur. Kod içinde

Log.e(">>>>>>>>>>>>>>>>>>", "Root elemtn body: "+soapObjectResultRoot.toString());

satırındaki outputa bakarsanız hiçbir formata uymayan bir data var ve o datayı parse etmek indexOf() metodu ile ancak yapılabiliyordu. DDMS e bakarsanız

Root elemtn body: GetGeoIPContextResponse{GetGeoIPContextResult=anyType{ReturnCode=1; IP=78.175.34.228; ReturnCodeDetails=Success; CountryName=Turkey; CountryCode=TUR; }; }

şeklinde saçma bir data görürsünüz. Bunun sebebi bodyIn ile sadece Root Element alınmasıdır. Yani çözüm önce rootu almak sonra istenilen result metodunundaki propertye erişmektir.

        	SoapObject soapObjectResultRoot=(SoapObject) soaSerializationEnvelope.bodyIn;
        	Log.e(">>>>>>>>>>>>>>>>>>", "Root elemtn body: "+soapObjectResultRoot.toString());
        	SoapObject soapObjectGetProperty=(SoapObject) soapObjectResultRoot.getProperty("GetGeoIPContextResult");

Bu linkte-GetGeoIPContext hangi metodu ve getProperty() ile hangi değerlere erişeceğimizi SOAP içinde yazıyor.
Uyarı örnek yapacağınız web servisi önce çalışıp çalışmadığını kontrol edin. Mesela şu anda Translation Engine çalışmıyor ve ben de bunun üzerinden deneme yapıyordum 🙂
1. ksoap2-android-assembly-2.4-jar-with-dependencies.jar indirdikten sonra assets içine atıp sonra sağ tıklayıp Build path->Add to build path tıklamanız yeterlidir. Ya da lib isminde bir klasör oluşturup onun altında atıp aynı şekilde sağ tıklayıp Build path->Add to build path ekletebilirisniz.
2. Erişeceğiniz http://www.webservicex.net/geoipservice.asmx?WSDL deki WSDL silip var olan public metodlarını iyice incelemektir. Sonra istediğinizi kullanabilirisniz.
3. AndroidManifest.xml içinde

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

ekleyin.

AndroidSoapActivity.java

package com.androidsoap;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class AndroidSoapActivity extends Activity {

	final static String NAMESPACE = "http://www.webservicex.net/";
	final static String METHOD_NAME = "GetGeoIPContext";
	final static String SOAP_ACTION = "http://www.webservicex.net/GetGeoIPContext";
	final static String URL = "http://www.webservicex.net/geoipservice.asmx?WSDL";
	
	TextView textView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView=(TextView) findViewById(R.id.textView1);
        SoapObject reSoapObject = new SoapObject(NAMESPACE, METHOD_NAME);
//Egerki sorgu çekecekseniz o zaman reSoapObject.addProperty(name,value); şeklinde değer eklemelisiniz. O da SOAP içinde belirtiliyor.
        SoapSerializationEnvelope soaSerializationEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        soaSerializationEnvelope.dotNet = true;
        soaSerializationEnvelope.setOutputSoapObject(reSoapObject);
        HttpTransportSE httpTransportSE = new HttpTransportSE(URL);
        int returnCode = 0;
        String ip = null, returnCodeDetail = null,countryName = null, countryCode = null;
        try {
        	httpTransportSE.call(SOAP_ACTION, soaSerializationEnvelope);
//Root elemente erişiyoruz.
        	SoapObject soapObjectResultRoot=(SoapObject) soaSerializationEnvelope.bodyIn;
        	Log.e(">>>>>>>>>>>>>>>>>>", "Root elemtn body: "+soapObjectResultRoot.toString());
//Root elementin altındaki erişeceğimiz metodun ..Result ile biten değerine erişiyoruz. Mesela METHOD_NAME = "GetGeoIPContext";
//Aşağıdaki metod ve parametre değerleri bulinkte açıklıyor zaten: http://www.webservicex.net/geoipservice.asmx?op=GetGeoIPContext
        	SoapObject soapObjectGetProperty=(SoapObject) soapObjectResultRoot.getProperty("GetGeoIPContextResult");
        	returnCode=Integer.parseInt(soapObjectGetProperty.getProperty("ReturnCode").toString());
        	ip=soapObjectGetProperty.getProperty("IP").toString();
        	returnCodeDetail=soapObjectGetProperty.getProperty("ReturnCodeDetails").toString();
        	countryName=soapObjectGetProperty.getProperty("CountryName").toString();
        	countryCode=soapObjectGetProperty.getProperty("CountryCode").toString();
        } catch (IOException e) {
        e.printStackTrace();
        } catch (XmlPullParserException e) {
        e.printStackTrace();
        }
        
        textView.setText("Return code --> "+returnCode+" \nIP --> "+ip+" \nReturn code details --> "+returnCodeDetail+" \nCountry name --> "+countryName+" \nCountry code --> "+countryCode);
        
    
    }
}

main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="230dp"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidsoap"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidSoapActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Download AndroidSoapSam.zip srouce code

Android içinde startActivityForResult() metodu ile başlatılan sub activitynin normal kapanıp kapanmadığına göre işlem yapabiliyoruz. Mesela devicedaki Back buttonuna basarak beklenmedik şekilde activity sonlandirabilir. Bazı durumlarda buna göre işlem yapmak zorunda kalıyoruz.

StartForResultActivity.java

package com.start.result;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class StartForResultActivity extends Activity {
	Button button1_ok;
	private static final int SHOW_SUBACTIVITY = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button1_ok=(Button) findViewById(R.id.button1);
        
        button1_ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(StartForResultActivity.this, SecondActivity.class);
				startActivityForResult(intent, SHOW_SUBACTIVITY);
			}
		});
    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
		case 1:
//Second activity normal olarak sonlanirsa RESULT_OK degeri döner.
			if(resultCode==Activity.RESULT_OK)
			{
				String string=data.getStringExtra("ethem");
				Toast.makeText(getApplicationContext(), "Inputed text: "+string, Toast.LENGTH_SHORT).show();
//Second activity beklendmedik sekilde kapanirsa(Mesela cihazdaki back buttonuna tikalnirsa) RESULT_CANCELED degeri doner.
			}else if(resultCode==Activity.RESULT_CANCELED){
				Toast.makeText(getApplicationContext(), "Beklenmedik sekilde second activity sonlandi", Toast.LENGTH_SHORT).show();
			}
			
			break;
		}
    
	}
	
}

SecondActivity.java

package com.start.result;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SecondActivity extends Activity{

	Button button;
	EditText editText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.second);
		button=(Button) findViewById(R.id.button1);
		editText=(EditText) findViewById(R.id.editText1);
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//Finish buttonuna tıklanarak activity sonlanirsa(yani beklediğimiz gibi) o zaman setResult(RESULT_OK, intent); değer dönderiyoruz StartForResultActivity activiysine. 
				Intent intent=new Intent();
				intent.putExtra("ethem", editText.getText().toString());
				setResult(RESULT_OK, intent);
				finish();
				
			}
		});
		
	}

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
    
    <Button android:text="Open Second Activity" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <EditText android:layout_width="match_parent" android:id="@+id/editText1" android:layout_height="wrap_content">
        <requestFocus></requestFocus>
    </EditText>
    <Button android:text="Finish" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    
</LinearLayout>

Download StartForResult.zip

Android ile PreferenceScreen içinde ListPreference içinde seçilen değer değiştiğinde gerçekleşen olay için basit bir örnek yazdım. findViewById() metoduna benzer bir erişim metodu var.

listPreference=(ListPreference) findPreference("customPreferences");

PreferenceScreen içinde aşağıdaki resimde görüldüğü gibi bazı özellikler tanımlayabiliyoruz. Android settings bununla yazılmış.

Çalıştırınca

MyPreferences.java

package com.preference.sam;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.widget.Toast;

public class MyPreferences extends PreferenceActivity {

	ListPreference listPreference;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//R.xml.pref ekliyoruz.
		addPreferencesFromResource(R.xml.pref);
//android:key="customPreferences" xml/pref.xml içindeki isim
		listPreference=(ListPreference) findPreference("customPreferences");
		listPreference.setOnPreferenceChangeListener(onPreferenceChangeListener);

	}
	
	OnPreferenceChangeListener onPreferenceChangeListener=new OnPreferenceChangeListener() {
		
		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
//Seçilen isme ait numara toast olarak görünüyor ve toast indeksi de log attiriyorum.
//pref.xml içinde android:entries="@array/names" ile görünecek bir dizi atiyoruz ve
//android:entryValues="@array/stud_num" kod ile de o diziye ait değerleri yazıyoruz.
//Bu iki dizi values/strings.xml içinde String array olarak tanımlanmıştır.
			Toast.makeText(getApplicationContext(), "Secilen ogrencinin okul numarasi : "+newValue, Toast.LENGTH_LONG).show();
			int index=listPreference.findIndexOfValue((String) newValue);
			Log.e(">>>>>>>>>>>>>>>>", "Index of selected value :" + index);
			return false;
		}
	};
	
}

pref.xml

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

    <PreferenceCategory android:title="Categori 1">
    	<ListPreference android:title="List Of Name"
    		android:key="customPreferences"
    		android:entries="@array/names"
    		android:entryValues="@array/stud_num">
    	</ListPreference>
    </PreferenceCategory>

</PreferenceScreen>

strings.xml

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

    <string name="hello">Hello World, PreferenceSamActivity!</string>
    <string name="app_name">PreferenceSam</string>
    <string-array name="names">
        <item >Ethem</item>
        <item >Isil</item>
    </string-array>
    <string-array name="stud_num">
        <item >060401029</item>
        <item > 1121000300</item>
    </string-array>

</resources>

Bunu main activity yaptım.
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.preference.sam"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity android:name="MyPreferences">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
      
    </application>

</manifest>

Download PreferenceSam.zip

Android içinde SahredPreferences verileri tutumak için kullanışlı bir yapıdır. Emülatörde /data/data/com.share.preferance/shared_prefs/ethem.xml olarak bakabilirisniz. Bazı uygulamalarda datalarınızı xml olarak tutma ihtiyacı için geliştirilmiş bir yapıtır. Buraya boolean, string, int, long ve float gibi veri tiplerini ekleyebilirsiniz. Aşağıdaki kod ile her activity create edildiğinde önceki verileri siliyorum.

        shEditor=sharedPreferences.edit();
        shEditor.clear();
        shEditor.commit();


ethem.xml dosyasını export etmek için aşağıdaki resimde kırmızı alanı tıklayın.

İçerik te aşağıdaki gibidir.

SharePrefereanceActivity.java

package com.share.preferance;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharePrefereanceActivity extends Activity {
	SharedPreferences sharedPreferences;
	SharedPreferences.Editor shEditor;
	Button button_save, button_show;
	static final private int share_pref_dialog = 1;
	StringBuilder stringBuilder;
	EditText editText_name, editText_age, editText_address;
	static int i=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button_save=(Button) findViewById(R.id.button1_save);
        button_show=(Button) findViewById(R.id.button2_show);
        editText_name=(EditText) findViewById(R.id.editText1_name);
        editText_age=(EditText) findViewById(R.id.editText2_age);
        editText_address=(EditText) findViewById(R.id.editText3_address);
        
        stringBuilder=new StringBuilder();
//ethem isminde bir xml oluşturuyor ve .edit() mtodu ile ekleme,silme ve güncelleme izni veriyoruz.
        sharedPreferences=getSharedPreferences("ethem", Activity.MODE_PRIVATE);
        shEditor=sharedPreferences.edit();
//Bu metod ile daha önceki kayıtları siliyoruz.
        shEditor.clear();
        shEditor.commit();
        button_save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int age=0;
				String name=editText_name.getText().toString();
				if(editText_age.getText().toString().length()>0)
				{
				age=Integer.parseInt(editText_age.getText().toString());
				}
				String address=editText_address.getText().toString();
				if(name.length()>0 && age>0 && address.length()>0)
				{
				create_share_preferences(name, age, address);
				}else{
					Toast.makeText(getApplicationContext(), "Check your inputs", Toast.LENGTH_LONG).show();
				}
			}
		});
        
        
        button_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//BUtton tıklanınca onCreateDialog() metodu içindeki dialog açılıyor.
				showDialog(share_pref_dialog);
				
			}
		});
        
        
        
        
    }
	private String reterieve_share_preferences() {
//.xml içindeki bütün kayıtları stringbuildera atıyoruz.
		 Map<String, ?> all_record = sharedPreferences.getAll();
		 Set set=all_record.entrySet();
		 Iterator it=set.iterator();
		 while (it.hasNext()) {
			 	Map.Entry map =(Map.Entry)it.next();
				stringBuilder.append(map.getKey()+" : "+map.getValue()+"\n");
				if(i%3==0)
				{
					stringBuilder.append("************\n");
				}
				i++;
		}
		

		return stringBuilder.toString();
	}
	private void create_share_preferences(String name,int age, String address) {
//Girilen kayıtları xml olarak kayıdediyor.
		shEditor.putString("name", name);
        shEditor.putInt("age", age);
        shEditor.putString("address", address);
        shEditor.commit();
        editText_name.setText("");
        editText_age.setText("");
        editText_address.setText("");
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		
		Builder alBuilder;
		switch(id) {
		case (share_pref_dialog) :
			alBuilder = new AlertDialog.Builder(this);
			alBuilder.setTitle("Do you want to show all records").
			setCancelable(false).setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
//ok seçilirse toast ile ekranda gösteriyorum.
									Toast.makeText(getApplicationContext(), reterieve_share_preferences(), Toast.LENGTH_LONG).show();

								}
							}).setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();

								}
							});
		return alBuilder.create();
		}
		return super.onCreateDialog(id);

	}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TableLayout android:layout_width="fill_parent" android:id="@+id/tableLayout1" android:layout_height="wrap_content">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Name :" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1"></TextView>
            <EditText android:id="@+id/editText1_name" android:layout_width="wrap_content" android:layout_height="wrap_content">
                <requestFocus></requestFocus>
            </EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView2" android:text="Age :"></TextView>
            <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:inputType="number" android:id="@+id/editText2_age"></EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView3" android:text="Address :"></TextView>
            <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:inputType="textPostalAddress" android:id="@+id/editText3_address"></EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save Input" android:id="@+id/button1_save"></Button>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Records" android:id="@+id/button2_show"></Button>
        </TableRow>
    </TableLayout>
</LinearLayout>

Bu arada com.share.preferance paket ismini yanlış yazmışım:)

Download SharePrefereance.zip

Android ile Twitter‘a benzer bir basit uygulama yazmaya çalıştım. Normalde uygulamaya login olurken username, profil image ve password sqlite veritabanında tutuluyor ve değerler oradan alınıyor ama örnek sade olsun diye o tarafa girmedim. Bu örneği daha iyi anlamak için Android Custom ListView Items and Adaptera bakabilirsiniz.

Uygulama image, user_name ve text alanalrından oluşuyor. En son girilen input en ListView‘de en üste ekleniyor.

BlipListActivity.java

package com.blip.list;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class BlipListActivity extends Activity {
    private ListView listView;
    private Button button_send_blip;
    private EditText editText_input_text;
    private BlipVar blipVar_obj;
    private BlipAdapter blipAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        listView=(ListView) findViewById(R.id.listView1_blip);
        button_send_blip=(Button) findViewById(R.id.button1_send);
        editText_input_text=(EditText) findViewById(R.id.editText1_input);
        Conf.arrayList.clear();
        
//        BlipVar object=new BlipVar();
//        object.setUser_name("mehmet");
//        object.setImage("http://www.ethemsulan.com/wp-content/themes/mahinhin/images/kelime.png");
//        object.setText("Merhaba bu bir textttir");
//		Conf.arrayList.add(object);
//Kendi adapterimizi yazdik ve listview ile ilişkilendirdik.
        blipAdapter=new BlipAdapter(this, Conf.arrayList);
        listView.setAdapter(blipAdapter);
        
        
        button_send_blip.setOnClickListener(send_blip);
    }
    
    OnClickListener send_blip=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			blipVar_obj=new BlipVar();
			blipVar_obj.setUser_name("isil");
			blipVar_obj.setImage("http://www.ethemsulan.com/wp-content/themes/mahinhin/images/kelime.png");
			blipVar_obj.setText(editText_input_text.getText().toString());
			Conf.arrayList.add(0, blipVar_obj);
//Adaptarimiza data girildiğinde kendisini güncelliyor ve girilen data hemen alta eklenir.
//Yani UI güncelleniyor.
			blipAdapter.notifyDataSetChanged();
			editText_input_text.setText("");
			
		}
	};
}

BlipAdapter.java

package com.blip.list;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class BlipAdapter extends ArrayAdapter<BlipVar>{
//BlipVar nesne listesi "names" ekleniliyor.
	private final Activity context;
	private ArrayList<BlipVar> names;

	public BlipAdapter(Activity context,ArrayList<BlipVar> names) {
//Bu username, textview ve image için layouyt oluşrurup nasıl gösterileceğine karar veriyoruz
//R.layout.blip_adapter
		
		super(context, R.layout.blip_adapter, names);
		this.context = context;
		
		this.names = names;
	}

	static class ViewHolder {
		public ImageView imageView;
		public TextView textView_user_name,textView_body_text;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		final ViewHolder holder;
		
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.blip_adapter, null, true);
			holder = new ViewHolder();
			holder.textView_user_name = (TextView) rowView.findViewById(R.id.textView1_user_name);
			holder.imageView = (ImageView) rowView.findViewById(R.id.imageView1);
			holder.textView_body_text=(TextView) rowView.findViewById(R.id.textView1_blip_text);
			rowView.setTag(holder);
		} else {
			holder = (ViewHolder) rowView.getTag();
		}
//Gelen obje içindeki dataları set ediyor.
		BlipVar blipVar=names.get(position);
		
		if(blipVar!=null)
		{
			holder.textView_user_name.setText(blipVar.getUser_name());
			holder.imageView.setImageDrawable(Conf.loadImageFromURL(blipVar.getImage()));
			
			holder.textView_body_text.setText(blipVar.getText());
		}		
		
		return rowView;
	}

}

BlipVar.java

package com.blip.list;

public class BlipVar {
//Adapterimizd ehang, alanalr varsa o alanalr tanimlanir.
	private String user_name,image,text;

	public String getUser_name() {
		return user_name;
	}

	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
	
}

Conf.java


package com.blip.list;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Conf {

	public static ArrayList<BlipVar> arrayList=new ArrayList<BlipVar>();
	
	//Internetten image cekiyor
	 public static Drawable loadImageFromURL(String url)
	    {
	    try
	    {
	    InputStream is = (InputStream) new URL(url).getContent();
	    Drawable d = Drawable.createFromStream(is, "src");
	    return d;
	    }catch (Exception e) {
	    System.out.println(e);
	    return null;
	    }
	 }
	
	private static InputStream OpenHttpConnection(String urlString) throws IOException
    {
		//Log.d(TAG, "InputStream");	
		InputStream in = null;
		while(in==null){
			int response = -1;
               
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
        
			if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        	
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.setReadTimeout(5000);
            httpConn.setConnectTimeout(5000);
            httpConn.connect();        
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
            }
        }
        return in;     
    }
	
	

}

blip_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:orientation="vertical">
    <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content" android:weightSum="1" android:baselineAligned="true">
        <ImageView android:src="@drawable/icon" android:id="@+id/imageView1" android:layout_height="50dip" android:layout_width="60dip" android:layout_marginLeft="10dip"></ImageView>
        <TextView android:text="TextView" android:layout_width="wrap_content" android:id="@+id/textView1_user_name" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="fill_parent" android:layout_marginLeft="50dip"></TextView>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:orientation="vertical">
        <TextView android:text="TextView" android:layout_width="wrap_content" android:id="@+id/textView1_blip_text" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_gravity="center"></TextView>
    </LinearLayout>
    
</LinearLayout>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
        <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/editText1_input" android:inputType="textMultiLine">
            <requestFocus></requestFocus>
        </EditText>
    </LinearLayout>
    <Button android:layout_gravity="right" android:text="@string/send_blip" android:id="@+id/button1_send" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    <ListView android:id="@+id/listView1_blip" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView>
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, BlipListActivity!</string>
    <string name="app_name">BlipList</string>
    <string name="send_blip">Send New Blip</string>
</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.blip.list"
      android:versionCode="1"
      android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BlipListActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Download BlipList.tar.gz

Android cihazınızın ekranını çevirirken veya döndürürken activity yeniden create ediliyor. Aşağıdaki uygulamada bar yüklenirken çevirdiğimizde activity recreate edildiğinden yarıda kalıyor ilerleme. Yani dolmuyor. Dolması için tekrar buttona basmamız gerekiyor.



OrientationSampActivity.java

package com.orientation;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class OrientationSampActivity extends Activity {
    private ProgressBar progressBar1;
    private Button button_bar;
    private Handler handler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        handler=new Handler();
        progressBar1=(ProgressBar) findViewById(R.id.progressBar1);
        button_bar=(Button) findViewById(R.id.button1_bar);
        progressBar1.setProgress(0);
//Cihazinizi cevirdiginizde(oriantasyon degistiginde) activity yeniden baslatiyor
//ve bar daha once kalinan yerde kaliyor. Yani barin tamamen dolmasş icin buttona tekrar tiklamaniz lazim.
        button_bar.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				handler.post(runaRunnable);
			}
		});
    }
    
    Runnable runaRunnable=new Runnable() {
		
		@Override
		public void run() {
			progressBar1.setProgress(progressBar1.getProgress()+1);
			
			if(progressBar1.getProgress()<100)
			{
				handler.postDelayed(runaRunnable, 100);
			}else{
				handler.removeCallbacks(runaRunnable);
			}
			
		}
	};
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ProgressBar 
    android:layout_height="wrap_content" 
    android:id="@+id/progressBar1" 
    style="?android:attr/progressBarStyleHorizontal" 
    android:layout_width="match_parent" 
    android:layout_marginTop="30px">
    </ProgressBar>
    <LinearLayout 
    android:layout_width="match_parent" 
    android:id="@+id/linearLayout1" 
    android:orientation="vertical" 
    android:layout_height="30dip">
    </LinearLayout>
    <Button 
    android:id="@+id/button1_bar" 
    android:layout_width="match_parent" 
    android:text="Start Bar" 
    android:layout_height="wrap_content">
    </Button>
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.orientation"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".OrientationSampActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Bu örneği indirip çalıştırınız ve progessbar yarıdayken cihazınızı döndürün: Download OrientationSamp

Sonra aşağıdaki kodu activitye ekleyin ve çalıştırıp tekrar dönderdiğinizde activityniz yeniden create edilmiyor.

android:configChanges="orientation|keyboardHidden"

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.orientation"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".OrientationSampActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Bu uygulama ile Android cihazının Mac Adresi, Modeli ve Manufacturer(Üretici) bilgilerini TextView’e yazmaya çalıştım. Android içinde

import android.os.Build; 

os paketinde bulunan Build static sınıfı ile bir Android cihazlarının birçok bilgilerine erişebiliyoruz. Mesela Build.HARDWARE gibi.

Android Device Information


Network bilgilerine
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

erişmesi için izin vermemiz lazım.
Ayrıca Wifi erişme izni de vermek lazım.

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

Android telefonumun bilgileri.

GetInfoActivity.java

package com.getinfo;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

public class GetInfoActivity extends Activity {
    
	private TextView mac,model,manufacturer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        model=(TextView) findViewById(R.id.textView1_model);
        mac=(TextView) findViewById(R.id.textView2_mac);
        manufacturer=(TextView) findViewById(R.id.textView3_manufacture);
        model.setText("Model => "+ Build.MODEL);
        
        String mac_adresi=get_mac_address();
		mac.setText("Mac => "+mac_adresi);
        manufacturer.setText("Manufacturer => "+Build.MANUFACTURER);
        
    }
    
    private String get_mac_address()
	{
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    
	    try{
	    	WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
	        WifiInfo wifiInf = wifiMan.getConnectionInfo();
	        return wifiInf.getMacAddress();
	    }
	    catch (Exception e) {
	    	return "00:00:00";
		}	
	}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:layout_height="wrap_content" android:text="" 
    android:layout_width="wrap_content" 
    android:id="@+id/textView1_model">
    </TextView>
    <TextView 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:layout_height="wrap_content" android:text="" 
    android:layout_width="wrap_content" 
    android:id="@+id/textView2_mac">
    </TextView>
    <TextView 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:layout_height="wrap_content" android:text="" 
    android:layout_width="wrap_content" 
    android:id="@+id/textView3_manufacture">
    </TextView>
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.getinfo"
      android:versionCode="1"
      android:versionName="1.0">
      
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GetInfoActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Download GetInfo.tar.gz

Android ile button tiklandiginda yazilan telefon numarasını arıyor.

tel:05357139804

tel: dan sonra telefon numaranızı yazıp test edin.

AndroidManifest.xml içinde arama izni aşağıdaki gibidir.

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

PhoneCallActivity.java

package com.call.phone;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class PhoneCallActivity extends Activity {
    private Button button_start_call;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button_start_call=(Button) findViewById(R.id.button1);
        
        button_start_call.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//Button tiklandiginda bu numara araniyor.
				Intent intent_call=new Intent(Intent.ACTION_CALL, Uri.parse("tel:05348762815"));
				startActivity(intent_call);
				Toast.makeText(getApplicationContext(), "Wait for call...", Toast.LENGTH_SHORT).show();
			}
		});
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button 
    android:id="@+id/button1" 
    android:text="Start Call" 
    android:layout_width="match_parent" 
    android:layout_height="200dip">
    </Button>
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.call.phone"
      android:versionCode="1"
      android:versionName="1.0">
      
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".PhoneCallActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Download source code PhoneCall.tar.gz

Android ile bir TextView değerlerini bold, underline ve italic yazmaya çalıştım.
Texview içine aşağıdaki özellikleri ekledim

android:textStyle="italic|bold|normal" 

Underline için de SpannableString isminde bir sınıf var.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
    android:layout_height="wrap_content" 
    android:id="@+id/textView1_underline" 
    android:text="TextView" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textStyle="italic|bold|normal"
    android:layout_width="wrap_content">
    </TextView>
</LinearLayout>

UnderlineTextActivity.java

package com.underline;

import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.ViewDebug.FlagToString;
import android.widget.TextView;

public class UnderlineTextActivity extends Activity {
    private TextView textView_underline;
    private SpannableString spString;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
//Yazilan textin altini çiziyorum.
        spString=new SpannableString("http://esulan.blogspot.com");
        spString.setSpan(new UnderlineSpan(), 0, spString.length(), 0);
        textView_underline=(TextView) findViewById(R.id.textView1_underline);
       
        textView_underline.setText(spString);
        
    }
}

Download UnderlineText.tar.gz