Volley Kütüphanesi Kullanımı

Volley, sunucu ile bağlantı kurup data alışverişi yapan bir kütüphane yapısıdır. Volley ile login, register veya veri göndermek için sunucuyla haberleşip projelerinizde rahatlıkla kullanabilirsiniz.

MacOs için localhost işlemleri için “Mamp” uygulamasını kullanabilirsiniz. Sunucu url için local sunucu ipyi kullanabilirsiniz. Bunun için de Php olarak web api yazmak gerekiyor.

Githubhttps://github.com/merttoptas/VolleyLoginRegister

  1. Projeye Volley Kütüphanesini Ekleme
implementation 'com.android.volley:volley:1.1.1'

Örnek uygulamada login, register ve veri paylaşımının olduğu activityler olacak.

2. DataBinding Ekleme

build.gradle de android scope ‘un altına yazalım.

dataBinding {
enabled = true
}

  2. LoginActivity ile Volley Login

Login ve register işlemleri için volley ile sunucuya request atıp daha sonra response almamız gerekiyor. Öncelikle login ekranını yapalım.

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

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="@drawable/background_main"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.LoginActivity">

<EditText
android:id="@+id/etLoginEmail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="27dp"
android:layout_marginTop="54dp"
android:layout_marginEnd="27dp"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/etLoginPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="27dp"
android:layout_marginTop="19dp"
android:layout_marginEnd="27dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etLoginEmail" />

<Button
android:id="@+id/btnLogin"
android:layout_width="100dp"
android:layout_height="35dp"
android:layout_marginStart="27dp"
android:layout_marginTop="21dp"
android:background="@drawable/login_btn_style"
android:text="Login"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etLoginPassword" />

<Button
android:id="@+id/btnRegister"
android:layout_width="100dp"
android:layout_height="35dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="29dp"
android:background="@drawable/login_btn_style"
android:text="Register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etLoginPassword" />

</android.support.constraint.ConstraintLayout>

</layout>


Drawable klasörüne "background.main.xml" adlı xml oluşturalım.

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

<gradient
android:angle="90"
android:endColor="@color/colorPrimary"
android:startColor="@color/colorPrimaryDark">

</gradient>

</shape>
login_btn_style.xml dosyasını da oluşturalım.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">


<solid android:color="#434e8c" />
<corners android:radius="50dp" />


</shape>

3. Login İşlemleri

LoginActivityde Volley için request kuyruğu oluşturmamız gerekiyor. Bunun için global alanda aşağıdakileri tanımlıyoruz.

LoginActivityBinding binding;
RequestQueue requestQueue;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
binding = DataBindingUtil.setContentView(this, R.layout.login_activity);
requestQueue = Volley.newRequestQueue(getApplicationContext());

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = sharedPreferences.edit();


binding.etLoginEmail.setText(sharedPreferences.getString("email",""));
binding.etLoginPassword.setText(sharedPreferences.getString("sifre", ""));

binding.btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

login(binding.etLoginEmail.getText().toString(), binding.etLoginPassword.getText().toString());


}
});

binding.btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});


}

Login işlemi için:

public void login(final  String email, final  String password ){
StringRequest request = new StringRequest(

Request.Method.POST,
"http:/192.168.1.54:8888/volley/login.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

if("100".equals(response)){


startActivity(new Intent(getApplicationContext(), LoggedActivity.class));

editor.putString("email", binding.etLoginEmail.getText().toString());
editor.putString("sifre", binding.etLoginPassword.getText().toString());
editor.commit();

finish();

}else if ("101".equals(response)){
Toast.makeText(getApplicationContext(), "Mail adresi veya şifre hatalı", Toast.LENGTH_SHORT).show();
}else if ("102".equals(response)){

Toast.makeText(getApplicationContext(), "Sunucu ile bağlantı yok", Toast.LENGTH_SHORT).show();
}

}
},

new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();

}
}

)
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> map = new HashMap<>();
map.put("email", email);
map.put("password",password);
return map;
}
};

requestQueue.add(request);
}

4. RegisterActivity

İlk olarak xml dosyası:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="@drawable/background_main"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.RegisterActivity">

<EditText
android:id="@+id/etRegisterNameSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:ems="10"
android:textColor="#FFFFFF"
android:textColorHint="#e6e6e6"
android:hint="Name Surname"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/etRegisterEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/etRegisterNameSurname"
android:layout_alignParentTop="true"
android:layout_marginTop="37dp"
android:ems="10"
android:textColor="#FFFFFF"
android:textColorHint="#e6e6e6"
android:hint="E-Mail"
android:inputType="textEmailAddress"
app:layout_constraintStart_toStartOf="@+id/etRegisterNameSurname"
app:layout_constraintTop_toTopOf="@+id/etRegisterNameSurname" />

<EditText
android:id="@+id/etCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etRegisterEmail"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Country"
android:textColor="#FFFFFF"
android:textColorHint="#e6e6e6"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="@+id/etRegisterEmail"
app:layout_constraintTop_toBottomOf="@+id/etRegisterEmail" />

<EditText
android:id="@+id/edtCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etCountry"
android:layout_alignStart="@+id/etRegisterEmail"
android:ems="10"
android:hint="City"
android:textColor="#FFFFFF"
android:textColorHint="#e6e6e6"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="@+id/etCountry"
app:layout_constraintTop_toBottomOf="@+id/etCountry" />

<EditText
android:id="@+id/edtRPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/etRegisterEmail"
android:layout_alignParentBottom="true"
android:layout_marginTop="7dp"
android:ems="10"
android:hint="password"
android:textColor="#FFFFFF"
android:textColorHint="#e6e6e6"
android:inputType="textPassword"
app:layout_constraintStart_toStartOf="@+id/edtCity"
app:layout_constraintTop_toBottomOf="@+id/edtCity" />

<Button
android:id="@+id/btn_Register"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_marginStart="4dp"
android:layout_marginTop="24dp"
android:background="@drawable/login_btn_style"
android:text="Register"
app:layout_constraintStart_toStartOf="@+id/edtRPassword"
app:layout_constraintTop_toBottomOf="@+id/edtRPassword" />

</android.support.constraint.ConstraintLayout>

</layout>

RegisterActivty için global alanda aşağıdakileri tanımlayalım.

RegisterActivityBinding binding;
RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);

queue = Volley.newRequestQueue(getApplicationContext());

binding = DataBindingUtil.setContentView(this,R.layout.register_activity);
binding.btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String city = binding.edtCity.getText().toString();
String country = binding.etCountry.getText().toString();
String email = binding.etRegisterEmail.getText().toString();
String password = binding.edtRPassword.getText().toString();
String namesurname = binding.etRegisterNameSurname.getText().toString();
fillData(city,country,email,namesurname,password);

}
});
}
private void fillData(final String city, final String country,final String email,final String nameSurname,final String password){
StringRequest postRequest = new StringRequest(
Request.Method.POST, // POST tipinde istekte bulunduk
"http:/10.1.17.167:8888/volley/kayit.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("RESPONSE",response);
// String response web sayfasından sonucu döndürecektir.
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("RESPONSE",error.getMessage());
}
}
){
@Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("city",city);
params.put("country",country);
params.put("email",email);
params.put("nameSurname",nameSurname);
params.put("password",password);
/*
POST tipinde ilgili sayfaya ilgili parametreleri gönder.
*/
return params;
}
};
queue.add(postRequest);
}

5. LoggedActivity

Burada volley ile yazı paylaşımını ve sunucudan gelen yazıları göstermeyi sağlayalım.

Layout klasörü içinde “yazı_ekle_layout” adlı xml oluşturalım.

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

<EditText
android:id="@+id/etIcerik"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="textMultiLine" />

<Button
android:id="@+id/btnEkle"
android:background="@drawable/login_btn_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="190dp"
android:text="İçeriği Ekle" />
</RelativeLayout>

“paylaşım_satiri” adlı xml dosyasını da aynı şekilde oluşturalım..

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">


<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvTarih"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="3dp"
android:text="TextView"
/>
<TextView
android:id="@+id/tvIcerik"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/tvTarih"
android:layout_alignParentTop="true"
android:layout_marginTop="96dp"
android:text="TextView"
/>

<TextView
android:id="@+id/tvMail"
android:layout_alignStart="@+id/tvTarih"
android:layout_alignParentTop="true"
android:layout_marginTop="51dp"
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>


</RelativeLayout>

</android.support.v7.widget.CardView>

</RelativeLayout>

activity_logged. xml dosyası:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity.LoggedActivity">

<ListView
android:id="@+id/listViewPaylasimlar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>

6. LoggedActivty’de Volley Paylaşım İşlemleri

Global alanda aşağıdakileri tanımlayalım:

PaylasimAdapter adapter;
ArrayList<Paylasim> paylasim = new ArrayList<>();
ListView listView;
SharedPreferences sharedPreferences;

RequestQueue queue;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged);

queue = Volley.newRequestQueue(getApplicationContext());
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

listView = findViewById(R.id.listViewPaylasimlar);

paylasimlariListele();

}
public void paylasimlariListele(){
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
"http:/192.168.1.54:8888/volley/paylasim_listele.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

Log.d("RESPONSE",response);

try {
JSONObject object = new JSONObject(response);

JSONArray array = object.optJSONArray("paylasimlar");
Log.d("DENEME", "Eleman Sayısı:"+ array.length());

int elemansayisi = array.length();

for (int i =0; i<elemansayisi; i++){

JSONObject eleman = array.getJSONObject(i);

int id = eleman.getInt("id");
String tarih = eleman.getString("tarih");
String paylasan_mail= eleman.getString("paylasan_mail");
String paylasim_icerik = eleman.getString("paylasim_icerik");


paylasim.add(
new Paylasim(
id,
tarih,
paylasan_mail,
paylasim_icerik
)
);

}

adapter = new PaylasimAdapter(paylasim,getApplicationContext());
listView.setAdapter(adapter);

} catch (JSONException e) {
e.printStackTrace();
}


}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}

){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
};
queue.add(stringRequest);
}
public  void  icerikEkle(final  String icerikYazisi){
StringRequest istek = new StringRequest(

Request.Method.POST,
"192.168.1.54:8888/volley/icerik_ekle.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

/*

gönderilen sayfadan gelen yanıtı yakalamadır.

*/

Log.d("OnRESPONSE",response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}

){
@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> map = new HashMap<>();
map.put("icerik", icerikYazisi);
map.put("mail", sharedPreferences.getString("email", "") );
return map;

/*
php sayfasına değer gönderme yeri

*/
}
};

queue.add(istek);

}

public void dialogCagir(){

final Dialog d = new Dialog(LoggedActivity.this);
d.setContentView(R.layout.yazi_ekle_layout);

final EditText etIcerik = d.findViewById(R.id.etIcerik);
Button btn = d.findViewById(R.id.btnEkle);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

icerikEkle(etIcerik.getText().toString());

d.dismiss();

}
});

d.show();
}.

7. PHP ile Login Api

  <?php
require_once("class.database_sqlite.php");


if($_SERVER['REQUEST_METHOD']=="POST"){

$email = $_POST['email'];
$password = $_POST['password'];


//header('Content-Type: application/json');
global $db2;
try{
// eğer mail adresi kayıtlıysa bunu, değilse bunu yap
if(selectCountInTable_OptionalValues_sqlite("User","email='".$email."' and password='".$password."'")==1){
echo "100";
}else{
echo "101";
}
/*
100 - kullanıcı adı ve şifre doğru
101 - kullanıcı adı veya şifre hatalı
102 - pdo exception

*/

}catch(PDOException $e){
echo "102";
}


}

?>

8. PHP ile Kayıt Api

 <?php
require_once("class.database_sqlite.php");

if($_SERVER['REQUEST_METHOD']=="POST"){


$city = $_POST['city'];
$country= $_POST['country'];
$email = $_POST['email'];
$nameSurname = $_POST['nameSurname'];
$password = $_POST['password'];
$kayit_tarih = date("d.m.Y H:i:s");


//header('Content-Type: application/json');
global $db2;
try{
// eğer mail adresi kayıtlıysa bunu, değilse bunu yap
if(selectCountInTable_OptionalValues_sqlite("User","email='".$email."'")==0){
/*
executeSqlite("INSERT INTO Rehber VALUES(NULL,'".$rehber_deviceid."','".$rehber_json."','".$rehber_tarih."')");
*/


executeSqlite("insert into User values(NULL,'".$nameSurname."','".$email."','".$country."','".$city."','".$password."','".$kayit_tarih."')");


}
echo "ok";
}catch(PDOException $e){
echo "fail";
}


}

?>

Githubhttps://github.com/merttoptas/VolleyLoginRegister

İnternet sitesi https://www.merttoptas.com
Yazı oluşturuldu 18

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

Benzer yazılar

Aramak istediğinizi üstte yazmaya başlayın ve aramak için enter tuşuna basın. İptal için ESC tuşuna basın.

Üste dön
%d blogcu bunu beğendi: