Site icon IT Tutorial

Android Programming -10 Sending Parameters Between Two Activities

Hi guys in this tutorial  we will talk about sending and receiving parameters between two activities.

In my previous tutorial, I talked about the transition between application page. If you have not read it yet, I recommend you read it first.

https://ittutorial.org/android-programming-9-switching-between-application-pages/

login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (kullanici_adi.getText()=="kubrahebes" && sifre.getText()=="12345") {
            Intent yeni_sayfa =new Intent(MainActivity.this, Anasayfa.Activity);
            yeni_sayfa.putExtra("isim", "kubraa");
            startactivity(yeni_sayfa);
        }
        else {
            mesaj.setText("Başarısız Giriş !!!");
        }
    }
});

since we have examined the code in detail previous article, I only share the codes in the  onclick method this day. if username and password are correct they will pass to the new page with intent method, we saw it in the previous lesson. today we will learn how sending parameters with intent. We can do this with putExtra method. The putExtra method works as key value. The first parameter we give to this method is key and the second parameter creates value. Key value is very important for us. Because we will get the value we send over the key value on the other page.

Just write this one line of code on the current page.  We also need to write code on the new page. It is as follows;

package com.example.mac.makale;

import android.content.Intent;
import android.os.Bundle;

public class YeniSayfaActivity extends AppCompatActivity{

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

Intent intent = getIntent();
        final String ad = intent.getStringExtra("isim");

Toast.makeText(this, ad, Toast.LENGTH_SHORT).show();

}

on this activity class we first import our libraries.  Then we name  our class name and extended it from the Activity class. After that we start to our codes in the oncreate method. We get the value from the other page again via intent class.  For this reason we create an object of intent class.  since the value from other page is a string, we define a variabla which type is string. With the intent class’s getStringExtra method, we capture the value from the other page and assign it to the variable we created.

Of course for the capture the correct value, we have to specify the key value when using this method. otherwise, the program does not know which value totake during compilation and gets an error.

Finally, we show the value from the other page with the message Toast.

 

Exit mobile version