How to pass values between fragments while using a viewpager in android - java

I am creating a sign up form which has been divided into three fragments.The three fragments are connected by a viewpager.I can traverse throught the fragments with next and previous buttons.I want the data from the first and second fragment to be available in the third fragment.One option is to use sharedpreferences.Is there any other approach.
The main class:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager)findViewById(R.id.myViewPager);
pager.setAdapter(pageAdapter);
}
public void selectFragment(int position){
pager.setCurrentItem(position, true);
// true is to animate the transaction
}
}
The main xml
<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"
tools:context=".MainActivity" >
<pl.looksok.viewpagerdemo.CustomViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The first fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentBlue extends Fragment {
Button btnnext1;
RelativeLayout frag1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
btnnext1=(Button) view.findViewById(R.id.btnnext1);
frag1=(RelativeLayout) view.findViewById(R.id.frag1);
btnnext1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(1);
}
});
return view;
}
}
The first xml:
<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:background="#4ECDC4"
android:id="#+id/frag1"
>
<Button
android:id="#+id/btnnext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="NEXT" />
<EditText
android:id="#+id/txtfname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmname"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="FIRST NAME" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtmname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtfname"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="MIDDLE NAME" />
<EditText
android:id="#+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmname"
android:layout_below="#+id/txtmname"
android:layout_marginTop="23dp"
android:ems="10"
android:hint="LAST NAME" />
<EditText
android:id="#+id/txtdob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtlname"
android:layout_centerVertical="true"
android:ems="10"
android:hint="DOB" />
</RelativeLayout>
The second fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentGreen extends Fragment {
Button btnnext2,btnprev2;
RelativeLayout frag2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_green, container, false);
btnnext2=(Button) view.findViewById(R.id.btnnext2);
btnprev2=(Button) view.findViewById(R.id.btnprev2);
frag2=(RelativeLayout) view.findViewById(R.id.frag2);
btnnext2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(2);
}
});
btnprev2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).selectFragment(0);
}
});
return view;
}
}
The second fragment's xml:
<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:background="#C7F464"
android:id="#+id/frag2"
>
<Button
android:id="#+id/btnnext2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="60dp"
android:text="NEXT" />
<Button
android:id="#+id/btnprev2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginRight="68dp"
android:layout_toLeftOf="#+id/btnnext2"
android:text="PREV" />
<EditText
android:id="#+id/txtgender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/btnnext2"
android:ems="10"
android:hint="GENDER" />
<EditText
android:id="#+id/txtmaritalstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtgender"
android:layout_below="#+id/txtgender"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="MARITAL STATUS" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtoccupation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmaritalstatus"
android:layout_below="#+id/txtmaritalstatus"
android:layout_marginTop="23dp"
android:ems="10"
android:hint="OCCUPATION" />
<EditText
android:id="#+id/txtusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtoccupation"
android:layout_centerVertical="true"
android:ems="10"
android:hint="USERNAME" />
<EditText
android:id="#+id/txtpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtusername"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="PASSWORD"
android:inputType="textPassword" />
</RelativeLayout>
The third fragment:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;
public class FragmentPink extends Fragment {
Button btnnext3,btnprev3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pink, container, false);
btnnext3=(Button) view.findViewById(R.id.btnnext3);
btnprev3=(Button) view.findViewById(R.id.btnprev3);
btnnext3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnprev3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).selectFragment(1);
}
});
return view;
}
}
The third fragment's xml:
<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:background="#FF6B6B">
<Button
android:id="#+id/btnnext3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="NEXT" />
<Button
android:id="#+id/btnprev3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="PREV" />
<EditText
android:id="#+id/txtaddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="ADDRESS" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtdistrict"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtaddress"
android:layout_below="#+id/txtaddress"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="DISTRICT" />
<EditText
android:id="#+id/txtstate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtdistrict"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="STATE" />
<EditText
android:id="#+id/txtpincode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtstate"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="PINCODE" />
</RelativeLayout>
The adapter:
package pl.looksok.viewpagerdemo;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FragmentBlue());
fragments.add(new FragmentGreen());
fragments.add(new FragmentPink());
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
I also created a class which has string values.I was wondering if i could create an object and set the fields as properties for that object
The class with the fields:
package pl.looksok.viewpagerdemo;
import java.io.Serializable;
public class RegistrationValues implements Serializable {
String fname;
String mname;
String lname;
String dob;
String gender;
String marital_status;
String occupation;
String username;
String password;
String address;
String district;
String state;
String pincode;
String nationality;
String email;
String phno;
String bank_acno;
String bank_branch;
String bank_ifsc;
String bank_swift;
}
So the question is how to pass the values in the first and second fragment to the last fragment without using Sharedpreferences.

The easy approach would be to let the RegistrationValues instance reside in your MainActivity instance:
public class MainActivity extends FragmentActivity {
ViewPager pager;
RegistrationValues values; //add this
public RegistrationValues getValues() { //add this
return values; //add this
}; //add this
In your fragments, use ((MainActivity) getActivity()).getValues() to update the values and to actually get the values in the third fragment or so.
Note: You should probably save the values instance in your MainActivity's onSaveInstance and restore it in your MainActivity's onCreate.

i think that for values passing between fragments you can use listener and dispatcher patterns and singleton pattern, which will manage listeners and dispatchers, because fragments are not Activities and you can't pass values via Intents.

A very common pattern is for the fragments to provide an interface by which values may be passed to them, and to use the containing activity as a hub. To see an example of this, use Eclipse or Android Studio to instantiate a new Master/Detail Flow activity and look at the code for the ListActivity.
But I would argue that in this case, you probably don't want to do that. Your data record looks like something you want to maintain in your persistence layer (Model), maybe mutate through a service (Controller) and pull up as needed into the fragment (View). Separate UI from business logic, and use an Adapter to keep the data in sync.

Related

Issues With Android App Recycler View Displaying User Thumb and User Name

I am programming a simple search for users but my app is not displaying the results of the query and crashes about 40% of the time after I click search. Here is my code. Any advice would be appreciated.
My Activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.MyApp.Objects.ParticipantsObject;
import com.MyApp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class ParticipantsActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighbors);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Participants");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(view -> {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(ParticipantsActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText);
FirebaseRecyclerOptions<ParticipantsObject> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ParticipantsObject>()
.setQuery(firebaseSearchQuery, ParticipantsObject.class)
.build();
class UserHolder extends RecyclerView.ViewHolder {
private TextView imageThumbTextView, nameTextView
UserHolder(View itemView) {
super(itemView);
imageThumbTextView = itemView.findViewById(R.id.profile_image);
nameTextView = itemView.findViewById(R.id.name_text);
}
void setUsers(ParticipantsObject participantsObject) {
String imageThumb = driverObject.getThumb_image();
imageThumbTextView.setText(imageThumb);
String name = participantsObject.getName();
nameTextView.setText(name);
}
}
FirebaseRecyclerAdapter<ParticipantsObject, UserHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ParticipantsObject, UserHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull UserHolder userHolder, int position, #NonNull ParticipantsObject participantsObject) {
userHolder.setUsers(participantsObject);
}
#Override
public UserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UserHolder(view);
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
}
My activity_participants.xml:
<?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:background="#ffffff"
tools:context="com.MyApp.ParticipantsActivity">
<TextView
android:id="#+id/heading_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Firebase Search"
android:textColor="#555555"
android:textSize="24sp" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/heading_label"
android:layout_below="#+id/heading_label"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_toStartOf="#+id/search_btn"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search here"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_field"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginRight="30dp"
android:background="#android:color/background_light"
app:srcCompat="#mipmap/search_button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_field"
android:layout_marginTop="50dp">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
My list layout:
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:srcCompat="#mipmap/ic_default_user" />
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="14dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="213dp"
android:layout_marginRight="20dp"
android:layout_toEndOf="#+id/profile_image"
android:text="Username"
android:textColor="#555555"
android:textSize="16sp" />
</RelativeLayout>
Anyone have any ideas as to why it's not displaying results?
My relevant Firebase DB basic paths are like so:
Users -> Participants -> UserIDs -> name, image, etc
Logcat isn't giving me much at the moment.

I was trying to add fragment via xml and print data fetched from fragment to MainActivity,but the code isn't running

Main Activity XML File
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.harsh1507.pc.t_1372.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:orientation="horizontal"
android:id="#+id/l1">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.harsh1507.pc.t_1372.Frag_a"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/tv"/>
</LinearLayout>
Main Activity JAVA File
package com.harsh1507.pc.t_1372;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements Frag_a.comm
{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv);
}
#Override
public void com(double s) {
tv.setText("Result is : "+Double.toString(s));
}
}
Fragment XML File
<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="horizontal"
tools:context="com.harsh1507.pc.t_1372.Frag_a">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:inputType="number"
android:id="#+id/ed1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/ed2"
android:inputType="number"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="cal"
android:id="#+id/btn"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rg"
android:orientation="vertical">
<RadioButton
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="ADD"
android:checked="true"
android:id="#+id/rb1"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="SUBSTRACT"
android:id="#+id/rb2"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="MULTIPLY"
android:id="#+id/rb3"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="DIVIDE"
android:id="#+id/rb4"/>
</RadioGroup>
</LinearLayout>
</LinearLayout>
Fragment JAVA File ,main problem may be present in this part but i am not able to debug that ,please go through the code and let me know where i missed something.
package com.harsh1507.pc.t_1372;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class Frag_a extends Fragment
{
View v;
comm c;
EditText ed1,ed2;
Button btn;
RadioGroup rg;
RadioButton rb1,rb2,rb3,rb4;
double d1,d2,comp;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
c=(comm) context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_frag_a, container, false);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
ed1=v.findViewById(R.id.ed1);
ed2=v.findViewById(R.id.ed2);
btn=v.findViewById(R.id.btn);
rb1=v.findViewById(R.id.rb1);
rb2=v.findViewById(R.id.rb2);
rb3=v.findViewById(R.id.rb3);
rb4=v.findViewById(R.id.rb4);
rg= v.findViewById(R.id.rg);
d1=Double.parseDouble(ed1.getText().toString());
d2=Double.parseDouble(ed2.getText().toString());
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (rb1.isChecked()) {
comp = d1 + d2;
c.com(comp);
}
if (rb2.isChecked()) {
comp = d1 - d2;
c.com(comp);
}
if (rb3.isChecked()) {
comp = d1 * d2;
c.com(comp);
}
if (rb4.isChecked()) {
comp = d1 / d2;
c.com(comp);
}
}
});
}
public interface comm{
void com(double s);
}
}
Make sure that ur main activity extends FragmentActivity instead of AppCompat.
The corresponding import would be :
import android.support.v4.app.FragmentActivity;
Any activities using fragments must be implemented as a subclass of FragmentActivity instead of the traditional Activity class

Activities togglebutton when clicking a part of an image

I'm currently trying to make a small application in java, and I have encountered a small problem.
I need to activate a togglebutton when I touch a particular area of the image that I have provided.
I enclose the code of my pages.
main.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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/btnPag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lights"
tools:ignore="HardcodedText" >
</Button>
<Button
android:id="#+id/btnPag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Automation"
tools:ignore="HardcodedText" >
</Button>
<Button
android:id="#+id/btnPag3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Garden"
tools:ignore="HardcodedText" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
</LinearLayout>
page1.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="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 1"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 2"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 3"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 4"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/casa"
tools:ignore="ContentDescription" />
</LinearLayout>
page2.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="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gate"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activates"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
page3.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="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Irrigation"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MercuryActivity.java
package it.anddev.bradipao.mercury;
// derived from http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MercuryActivity extends FragmentActivity implements Page1Fragment.OnPageListener {
// list contains fragments to instantiate in the viewpager
List<Fragment> fragments = new Vector<Fragment>();
// page adapter between fragment list and view pager
private PagerAdapter mPagerAdapter;
// view pager
private ViewPager mPager;
// activity data
public String p2text,p3text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// creating fragments and adding to list
fragments.add(Fragment.instantiate(this,Page1Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Page2Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Page3Fragment.class.getName()));
// creating adapter and linking to view pager
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),fragments);
mPager = (ViewPager) super.findViewById(R.id.pager);
mPager.setAdapter(this.mPagerAdapter);
// upper bar button listener, allows direct page access
Button button = (Button)findViewById(R.id.btnPag1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0); // go to first page
}
});
button = (Button)findViewById(R.id.btnPag2);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(1); // go to second page
}
});
button = (Button)findViewById(R.id.btnPag3);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(2); // go to third page
}
});
}
// page 1 fragment listener implementation
#Override
public void onPage1(String s) {
// set activity data with received string
p2text = new String(s+" 2");
p3text = new String(s+" 3");
// page 2 fragment update
Page2Fragment f2 = (Page2Fragment) fragments.get(1);
f2.ptext = p2text;
// if page 2 view is already created, update
View v2 = f2.getView();
if (v2!=null) {
}
// page 3 fragment update
Page3Fragment f3 = (Page3Fragment) fragments.get(2);
f3.ptext = p3text;
// if page 3 view is already created, update
View v3 = f3.getView();
if (v3!=null) {
}
}
}
Page1Fragment.java
package it.anddev.bradipao.mercury;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class Page1Fragment extends Fragment {
public String ptext="..PAGE 1..";
// activity listener interface
private OnPageListener pageListener;
public interface OnPageListener {
public void onPage1(String s);
}
// onAttach : set activity listener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// if implemented by activity, set listener
if(activity instanceof OnPageListener) {
pageListener = (OnPageListener) activity;
}
// else create local listener (code never executed in this example)
else pageListener = new OnPageListener() {
#Override
public void onPage1(String s) {
Log.d("PAG1","Button event from page 1 : "+s);
}
};
}
// onCreateView :
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page1,container,false);
// update text
return view;
}
// set text helper function
}
Page2Fragment.java
package it.anddev.bradipao.mercury;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class Page2Fragment extends Fragment {
public String ptext="..PAGE 2..";
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page2,container,false);
// update text
return view;
}
// set text helper function
}
Page3Fragment.java
package it.anddev.bradipao.mercury;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class Page3Fragment extends Fragment {
Button btnWrite;
public String ptext="..PAGE 3..";
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page3,container,false);
// update text
return view;
}
}
PageAdapter.java
package it.anddev.bradipao.mercury;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
// fragments to instantiate in the viewpager
private List<Fragment> fragments;
// constructor
public PagerAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
// return access to fragment from position, required override
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
// number of fragments in list, required override
#Override
public int getCount() {
return this.fragments.size();
}
}

Android - Controls resolve to null

I'm writing a decimal time converter for someone, and I am trying to use findViewById to access some of my controls. So, I assign each of them, and then I assign an onclick listener to a button(btnConvert). When I assign the listener, the app crashes due to the fact that btnConvert is null. I have read into this, but I haven't found a working solution yet. Please refer to my code below
MainActivity.java:
package com.alex_justi.dec2time;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
static EditText inDec;
static Button btnConvert;
static TextView outHours;
static TextView outMinutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
inDec = (EditText)rootView.findViewById(R.id.dec);
btnConvert = (Button)rootView.findViewById(R.id.convert);
outHours = (TextView)rootView.findViewById(R.id.hours);
outMinutes = (TextView)findViewById(R.id.minutes);
return rootView;
}
}
}
fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
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"
tools:context="com.alex_justi.dec2time.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Decimal Time" />
<EditText
android:id="#+id/dec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Button
android:id="#+id/convert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/dec"
android:text="Convert" />
<TextView
android:id="#+id/minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/hours"
android:layout_marginTop="15dp"
android:text="Minutes: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/convert"
android:text="Hours: "
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Add the listeners in your fragment onCreateView() after you've obtained the references with rootView.findViewById().

App Crashing when using onCreate Eclipse [Beginner]

This is so simple but I have no idea why it's crashing when I click a button.... It's meant to just change the TextView on the activity.
Code is below:::::
MainActivity:
package com.example.databasetut;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void displayText(String message) {
TextView textView = (TextView) findViewById(R.id.textDisplay);
textView.setText(message);
}
public void onClick_AddRecord(View v) {
displayText("Clicked add record");
}
public void onClick_ClearAll(View v) {
displayText("Clicked clear all");
}
public void onClick_DisplayRecords(View v) {
displayText("Clicked display record");
}
}
activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/textDisplay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.databasetut.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:onClick="onClick_DisplayRecords"
android:text="Display" />
<Button
android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="onClick_ClearAll"
android:text="Clear" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="29dp"
android:onClick="onClick_AddRecord"
android:text="Add" />
<TextView
android:id="#+id/textDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
What's the problem here?!
You have given android:id="#+id/textDisplay" to both RelativeLayout and to TextView so error occurs.
Change the id of RelativeLayout or TextView your problem will be solved.
I dont think that you're alowed to use uppercase letters in view Id's in your xml layout. So the fix will be to change android:id="#+id/textDisplay" to ex. android:id="#+id/text_display". Plus remove android:id="#+id/textDisplay" from your RelativeLayout keep this id only on your textview

Categories

Resources