DHRUV THAKKAR
DHRUV THAKKAR

Reputation: 23

How to use layout elements in Fragment Class

Here I made a Navigation Bar in Android using Fragment.
Now I need to print my data using Fragment class and its XML file, but I am unable to get the id in a normal manner.

Profile.java

        package com.example.dhruv.dez;

    import android.app.Activity;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;

    public class Profile extends Fragment {
        @Nullable

   //Below Line Gives Error
   BackgroundTask b = new BackgroundTask(this);

    TextView t1;

        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.profile, container, false);

        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            //Below Line Gives Error
            t1=FindViewById(R.id.username);

            getActivity().setTitle("PROFILE");


        }

    }

profile.xml

        <?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">


    <TextView
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:text="PROFILE"
        android:id="@+id/username"/>

    </RelativeLayout>

BackgroundTask.java

        public class BackgroundTask extends AsyncTask<String,Void,String>{

        Context ctx;

        public BackgroundTask(Context ctx)
        {
            this.ctx=ctx;
        }

        @Override
        protected String doInBackground(String... params) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            String work = params[0];

            if (work.equals("register")) {

                String name= params[1];
                String email = params[2];
                String mobno= params[3];
                String pass = params[4];
                try {
                    String login_url = "http://myweb.in/dhruv/signup.php";
                    URL url = new URL(login_url);
                    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                    huc.setRequestMethod("POST");
                    huc.setDoOutput(true);
                    OutputStream os = huc.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&"

                            + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") +"&"
                            + URLEncoder.encode("mobno", "UTF-8") + "=" + URLEncoder.encode(mobno, "UTF-8") +"&"
                            + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
                    Log.w("Error", data);
                    bw.write(data);
                    bw.flush();
                    bw.close();
                    os.close();
                    InputStream is = huc.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
                    String respone = br.readLine();
                    Log.w("Response", respone);
                    is.close();
                    return respone;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

Why can't I use Background task object in my fragment class? May I know why is there this problem?
And Is using fragmnets in Android projects safe?
Are there any better ways to do this?

Upvotes: 1

Views: 1360

Answers (6)

Edalat Feizi
Edalat Feizi

Reputation: 1401

In fragmentsfor initializing views and use them you should inflate fragment layout and save it inside a Viewvariable just like this:

package com.example.dhruv.dez;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Profile extends Fragment {
    @Nullable
    private TextView t1;
    private View rootView;//View variable to save fragment layout and use it to initialize views and use them
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 
    Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.profile, container, false);

        t1 = rootView.findViewById(R.id.username);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        getActivity().setTitle("PROFILE");


    }

}

and if you need to pass context to a class like your declared BackgroundTask you should pass context this way:

BackgroundTask b = new BackgroundTask(getActivity());

fore more information about AsyncTaskin android see this android official documentation about it

Upvotes: 1

Syed Danish Haider
Syed Danish Haider

Reputation: 1384

In fragment class you can use inflater to attach layout as shown in below. and u can acess elements as:

public class BlankFragment3 extends Fragment {

public BlankFragment3() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_blank3, container, false);
     //element of xml file
    TextView mTxtTitle = (TextView) view.findViewById(R.id.txtTitle);
    mTxtTitle.setText("Helooooooo")

    return view;
}

}

Upvotes: 0

Roberto Manfreda
Roberto Manfreda

Reputation: 2623

Try this:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile, container, false);

    t1 = view.findViewById(R.id.username);
    //do stuff with t1 obj

    return view;
}

Upvotes: 0

Kannan_SJD
Kannan_SJD

Reputation: 1072

This layout is in your view parameter of onViewCreated lifecycle callback .. So use view.findViewById(YOUR_ID). It should work. Or you could use getView() method in your onActivityCreated() callback as well..

Can I know why is there problem. And Is using fragmnets in android projects safe? Are there any better ways to do this?

Yes definitely. Its actually a good practice to use fragments when you have a more manipulating UI that keep changing and the lifecycle callbacks are well formed when using fragments. Learn more about

Fragment transactions and Fragments

here..

BackgroundTask is hopefully your custom class and is not expecting a fragments instance.. Check the argument of Background task, if it is looking for context pass getActivity()

Upvotes: 0

glm9637
glm9637

Reputation: 894

You are trying to use the functionality of a activity, but fragments are a whole lot different from them. You need to find the views inside the RootView, so you would need to change the line to:

t1 = view.findViewById(R.id.username)

Also you should probably read a bit more about fragments if you are unsure how to use them. A good starting point probably would be https://developer.android.com/guide/components/fragments

Upvotes: 0

Bubu
Bubu

Reputation: 1543

In a fragment you must use :

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    t1 = (TextView) view.findViewById(R.id.username);
    getActivity().setTitle("PROFILE");
}

Upvotes: 0

Related Questions