I want to change the text in message when the button is clicked to "Hello World!".The idea would be that it would use a method inorder to change the text from a blank TextView into one that has writing on.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Button"
tools:layout_editor_absoluteX="158dp"
tools:layout_editor_absoluteY="282dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.clickmeapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View message){
message.text="Hello World!";
}
}
Any help in solving this issue would be amazing.
In my code, when you click the button, you will see the "Hello World!" text.
xml
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add this code
//Button Click
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Set TextView
setMessage("Hello World!");
}
});
}
public void setMessage(String message){
findViewById(R.id.message).setText(message);
}
Related
I'm trying to replace a fragment in a tabbed activity with another, when I search online I find people using FragmentLayout or View but I can't find a solution that works. This is my first application, sorry if the code is not optimized.
MainActivity.java :
`
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public ViewPager viewPager;
public FragmentAbstract fragmentActuel;
public FragmentAbstract fragmentAncien;
public VPAdapter vpAdapter;
public String message;
public ViewModelFactory viewModelFactory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//on récupere le container des tableau par son id
TabLayout tabLayout = findViewById(R.id.tabs);
//page de base
viewPager = findViewById(R.id.view_pager);
//on definit la page de base
tabLayout.setupWithViewPager(viewPager);
viewModelFactory = new ViewModelFactory(this);
//on ajouter les fragments dans la page de base
this.vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.fragmentActuel = new Fragment_repetition_home(this);
this.fragmentAncien = fragmentActuel;
vpAdapter.addfragment(fragmentActuel,"REPETITION");
vpAdapter.addfragment(new Fragment_technique_home(this),"TECHNIQUE");
vpAdapter.addfragment(new Fragment_figure_home(this),"FIGURE");
viewPager.setAdapter(vpAdapter);
//pour dire que l'on veut 3 pages en arrière plan
viewPager.setOffscreenPageLimit(3);
}
}
VPAdapter.java :
public class VPAdapter extends FragmentPagerAdapter {
private ArrayList<FragmentAbstract> fragmentArrayList = new ArrayList<>();
private final ArrayList<String> fragmentTitle = new ArrayList<>();
public VPAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
public void addfragment(FragmentAbstract fragment, String title){
fragmentArrayList.add(fragment);
fragmentTitle.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitle.get(position);
}
//pour changer les fragments dans la liste
public void changeFragment(MainActivity mainActivity) {
if (!mainActivity.fragmentAncien.equals(mainActivity.fragmentActuel)) {
int index = fragmentArrayList.indexOf(((FragmentAbstract) mainActivity.vpAdapter.getItem(mainActivity.viewPager.getCurrentItem())));
fragmentArrayList.set(index,mainActivity.fragmentActuel);
}
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.MonProgramme.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REPETITION"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FIGURE"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TECHNIQUE"/>
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
fragment_figure_home.xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/figure_home"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/selection_figure"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true">
</ListView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/button_plus_figure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="#dimen/fab_margin"
android:layout_marginBottom="16dp"
android:src="#drawable/ic_plus"
android:backgroundTint="#color/grey_2"
android:onClick="onClick"/>
</FrameLayout>
Do you have a idea for replace the fragment not superimposed ?
I'm new in android studio.
I'm hope to open url with User.java(has been data-binding), but the code is not working.
Could someone give some advice?
Thanks
Edit: OpenURL method is called in activity_main.xml
Edit: I have found problems.
User.java
public class User {
Context context;
String url;
public User(Context context, String url) {
this.context = context;
this.url = url;
}
public void OpenURL() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User(getApplicationContext(),"https://www.google.com.tw/?hl=zh_TW");
activityMainBinding.setUser(user);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.rl.mp_a.User" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button"
android:onClick="#{() -> user.OpenURL()}"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
so i wanted to creat a footer navigtion on the main activity and a fragment view above it
but now when i try to use the normal navigtion with the navigtion grafh it just crashes.
mainActivity java code:
package com.example.mywatchlist;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button homeBtn = findViewById(R.id.homeBtn);
Button profileBtn = findViewById(R.id.profileBtn);
Button socialBtn = findViewById(R.id.theSocialSearchBtn);
Button contentBtn = findViewById(R.id.contentContentSearchBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment home = new homeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView,home).commit();
}
});
profileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userProfileFragment profile = new userProfileFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView,profile).commit();
}
});
socialBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
socialSearchFragment social = new socialSearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView,social).commit();
}
});
contentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contentSearchFragment contentSearch = new contentSearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView,contentSearch).commit();
}
});
}
}
main activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="632dp"
app:defaultNavHost="true"
app:navGraph="#navigation/navigation" />
<LinearLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Go to\nHome"
android:textSize="12dp" />
<Button
android:id="#+id/profileBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="My\nProfile"
android:textSize="12dp" />
<Button
android:id="#+id/theSocialSearchBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Search for\nPeople"
android:textSize="12dp" />
<Button
android:id="#+id/contentContentSearchBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Search for\nContent"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
and now it crashes when i try to move in this fragment:
fragment to move from java code:
package com.example.mywatchlist;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {#link Fragment} subclass.
* Use the {#link contentSearchFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class contentSearchFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public contentSearchFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment contentSearchFragment.
*/
// TODO: Rename and change types and number of parameters
public static contentSearchFragment newInstance(String param1, String param2) {
contentSearchFragment fragment = new contentSearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content_search,container, false);
// Inflate the layout for this fragment
Button searchBtn = view.findViewById(R.id.contentContentSearchBtn);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Navigation.findNavController(view).navigate(R.id.action_contentSearchFragment_to_contentFragment);
}
});
return view;
}
}
and this is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".contentSearchFragment" >
<TextView
android:id="#+id/contentSearchTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#C4FF80"
android:gravity="center"
android:text="Content search"
android:textSize="30dp" />
<Button
android:id="#+id/contentSearchAddNewContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add new content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFEB3B"
android:orientation="horizontal">
<EditText
android:id="#+id/contentSearchBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#C8C8C8"
android:ems="10"
android:hint="Search for content"
android:inputType="textPersonName"
android:minHeight="48dp" />
<Button
android:id="#+id/contentContentSearchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="502dp">
<TextView
android:id="#+id/contentSearchData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="test\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntesttest\ntest\ntest\ntest\ntest\ntest\XXXXXXXXXXXXXXXXXXntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\nXXXXXXXXXXXXXXXXX test\ntest\nXXXXXXXXXXXXXXXX\ntest\ntest\ntest\ntest\ntest" />
</ScrollView>
</LinearLayout>
and this is the navigtion xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/navigation"
app:startDestination="#id/startFragment">
<fragment
android:id="#+id/startFragment"
android:name="com.example.mywatchlist.startFragment"
android:label="fragment_start"
tools:layout="#layout/fragment_start" >
<action
android:id="#+id/action_startFragment_to_logInFragment"
app:destination="#id/logInFragment" />
<action
android:id="#+id/action_startFragment_to_registerFragment"
app:destination="#id/registerFragment" />
</fragment>
<fragment
android:id="#+id/logInFragment"
android:name="com.example.mywatchlist.logInFragment"
android:label="fragment_log_in"
tools:layout="#layout/fragment_log_in" >
<action
android:id="#+id/action_logInFragment_to_homeFragment"
app:destination="#id/homeFragment" />
</fragment>
<fragment
android:id="#+id/registerFragment"
android:name="com.example.mywatchlist.registerFragment"
android:label="fragment_register"
tools:layout="#layout/fragment_register" >
<action
android:id="#+id/action_registerFragment_to_homeFragment"
app:destination="#id/homeFragment" />
</fragment>
<fragment
android:id="#+id/homeFragment"
android:name="com.example.mywatchlist.homeFragment"
android:label="fragment_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/userProfileFragment"
android:name="com.example.mywatchlist.userProfileFragment"
android:label="fragment_user_profile"
tools:layout="#layout/fragment_user_profile" />
<fragment
android:id="#+id/contentFragment"
android:name="com.example.mywatchlist.contentFragment"
android:label="fragment_content"
tools:layout="#layout/fragment_content" />
<fragment
android:id="#+id/contentSearchFragment"
android:name="com.example.mywatchlist.contentSearchFragment"
android:label="fragment_content_search"
tools:layout="#layout/fragment_content_search" >
<action
android:id="#+id/action_contentSearchFragment_to_contentFragment"
app:destination="#id/contentFragment" />
</fragment>
<fragment
android:id="#+id/socialSearchFragment"
android:name="com.example.mywatchlist.socialSearchFragment"
android:label="fragment_social_search"
tools:layout="#layout/fragment_social_search" >
<action
android:id="#+id/action_socialSearchFragment_to_userProfileFragment"
app:destination="#id/userProfileFragment" />
</fragment>
</navigation>
crashing:
--------- beginning of crash
2022-07-01 14:32:49.986 25363-25363/com.example.mywatchlist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mywatchlist, PID: 25363
java.lang.IllegalStateException: View com.google.android.material.button.MaterialButton{3bedc11 VFED..C.. ...P.... 921,5-1440,173 #7f080237 app:id/contentContentSearchBtn} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.kt:71)
at com.example.mywatchlist.contentSearchFragment$1.onClick(contentSearchFragment.java:73)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1194)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2022-07-01 14:32:50.027 25363-25363/com.example.mywatchlist I/Process: Sending signal. PID: 25363 SIG: 9
thank you to all the helpers
can you please share the crashing error? It's hard to figure out the error. If you can also add how to reproduce the crash it can be very helpful
You forgot to initialize NavHostFragent
so kindly Initiliaze In your OnCreate
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id. fragmentContainerView);
NavController navController = navHostFragment.getNavController();
and for the navigate one fragment to another fragment use navigate
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {navController.navigate(R.id. action_startFragment_to_registerFragment
}
});)
How can I make a radio button group and a TextField, so that whenever I click on TextField the radio button automatically changes from one to another?
Please give me a block of code for this.
If I understood your question correctly, you want the radioButton checked status change once the textView click. You can achieve by this way.
public class MainActivity extends Activity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton,male,female;
private TextView btnDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);
btnDisplay=(TextView)findViewById(R.id.textView3);
male = (RadioButton)findViewById(R.id.radioButton);
female=(RadioButton)findViewById(R.id.radioButton2);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
if(radioSexButton.getText().toString().equals("Male"))
{
female.setChecked(true);
}
else
{
male.setChecked(true);
}
}
});
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="#+id/radioGroup"
android:layout_alignRight="#+id/textView3"
android:layout_alignEnd="#+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="#+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="#+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me "
android:id="#+id/textView3"
android:textSize="35dp"
android:layout_below="#+id/radioGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"></TextView>
</RelativeLayout>
https://www.tutorialspoint.com/android/android_radiogroup_control.htm
check this link , to use radio group with textviews
I'm new to android development and trying to create a simple register application but the application crash every time I click the Register Here TextView. Other than that, I code the login button to try the calling of another activity but it has no respond after I click the button. I tried so hard to find the mistakes but I'm not sure that what I missed in the coding.
This is the main activity
package com.fyp4201.universityguide;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabHost host = (TabHost) findViewById(R.id.tabHost);
host.setup();
//Tab 1
TabHost.TabSpec spec = host.newTabSpec("tab1");
spec.setContent(R.id.tab1);
spec.setIndicator("Home");
host.addTab(spec);
//Tab 2
spec = host.newTabSpec("tab2");
spec.setContent(R.id.tab2);
spec.setIndicator("Search Courses");
host.addTab(spec);
//Tab 3
spec = host.newTabSpec("tab3");
spec.setContent(R.id.tab3);
spec.setIndicator("Search University");
host.addTab(spec);
//Tab4
spec = host.newTabSpec("tab4");
spec.setContent(R.id.tab4);
spec.setIndicator("Compare Universities");
host.addTab(spec);
//Tab5
spec = host.newTabSpec("tab5");
spec.setContent(R.id.tab5);
spec.setIndicator("Ranking of Universities");
host.addTab(spec);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch( item.getItemId()){
//noinspection SimplifiableIfStatement
case R.id.action_settings: {
return true;
}
case R.id.action_login:{
Intent intent= new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
}
default:
return super.onOptionsItemSelected(item);
}
}}
This is codes for login activity
package com.fyp4201.universityguide;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView regis = (TextView) findViewById(R.id.register);
Button login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Homeafterlogin.class);
LoginActivity.this.startActivity(intent);
}
});
regis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, Register.class);
LoginActivity.this.startActivity(intent);
}
});
}}
This is codes for Register activity
package com.fyp4201.universityguide;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
private static final String REGISTER_URL = "http://jrfyp4201.site88.net/volleyRegister.php";
public static final String KEY_USERNAME = "username";
public static final String KEY_NAME = "name";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
public static final String KEY_CONTACTNO = "contactno";
private EditText etname,etuname,etpass,etconpass,etemail,etcontactno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etname= (EditText) findViewById(R.id.name);
etuname= (EditText) findViewById(R.id.uname);
etpass= (EditText) findViewById(R.id.pass);
etconpass= (EditText) findViewById(R.id.conpass);
etemail= (EditText) findViewById(R.id.email);
etcontactno= (EditText) findViewById(R.id.contactno);
}
public void onRegisterbtnClick(View view ){
registerUser();
}
public void registerUser(){
final String username = etuname.getText().toString().trim();
final String password = etpass.getText().toString().trim();
final String name = etname.getText().toString().trim();
final String email = etemail.getText().toString().trim();
final String contactno = etcontactno.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Register.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_NAME, name);
params.put(KEY_EMAIL, email);
params.put(KEY_CONTACTNO, contactno);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
This is the logcat error file
Process: com.fyp4201.universityguide, PID: 20646
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fyp4201.universityguide/com.fyp4201.universityguide.Register}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.fyp4201.universityguide.Register.onCreate(Register.java:20)
at android.app.Activity.performCreate(Activity.java:5340)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
XML files of register activity
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.fyp4201.universityguide.Register"
tools:showIn="#layout/activity_register">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name :"
android:id="#+id/textView2" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username :"
android:id="#+id/textView3" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edituname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password :"
android:id="#+id/textView4" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editpass"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirm Password :"
android:id="#+id/textView7" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editconpass"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E-mail address :"
android:id="#+id/textView5" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/editemail"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact Number :"
android:id="#+id/textView6" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/editcontactno"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:id="#+id/registerbtn"
android:layout_gravity="center_horizontal"
android:onClick="onRegisterbtnClick" />
</LinearLayout>
XML file of login activity
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.fyp4201.universityguide.LoginActivity"
tools:showIn="#layout/activity_login2">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:id="#+id/textView1" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/loginuname" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/loginpass" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/login"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusableInTouchMode="false"
android:onClick="onLoginClick" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Register Here!"
android:id="#+id/register"
android:layout_gravity="center_horizontal"
android:textColor="#color/accent_material_light"
android:clickable="true"
android:onClick="onRegisterClick" />
</LinearLayout>
Please tell me what I missed. Thank you.
Check all the ids in the xml files and correct their name in java.
It seems like you are referencing an id of another xml file thats not associated with this activity like you might be refering a username field of login xml file in registration activity and vice versa
Nvm, i fixed the problem. There's no problem with the codings just the application is not updated after changes had been made. It is fixed after i clean and rebuild the project. Thank you .