简体   繁体   中英

Access fragment from activity besides main activity

I have an existing application that I am trying to modify and could really use some help.

It is a chat application. The original flow of the application was as follows: Launch-> Splash Screen Activity-> MainActivity (extending Actionbar Sherlock)

Once in the main activity the default fragment is the ChatRoomFragment. From there you can select different tabs and interact with the application.

What I would like to change about the flow to is the following: Launch->Splash Screen Activity-> Terms of Service/Sign -> MainMenu->MainActivity

I have created the mainmenu layout to contain 4 buttons. Join, Search, Profile, Settings

Here is the problem. My Join button works fine, onClick simply triggers the intent to start MainActivity and and the chat room loads. From this screen you can access the different tabs and fragments within the application.

However, I now would like to have the "search" button set to open a dialog. With a editText field and a search button. Upon clicking search it should pass the search string to the PlacesSearchFragment and populate results.

I copied the code from within my application where this search is normally completed (inside the ChatRoomsFragment but it will not work from within my mainMenu Activity.

How do I start the new fragment from the menu activity??

Code Below:

  menuActivity.java
package com.peekatucorp.peekatu;

//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class menuActivity extends Activity implements ActionBar.TabListener {
    Button b1;
    Button b2;
    Button b3;
    EditText txtsearch;
    final private static int DIALOG_LOGIN = 1;
    final private static int DIALOG_FORGET = 2;
    final private static int DIALOG_SEARCH = 3;
    private android.app.FragmentTransaction ft;



@Override
public void onCreate(Bundle savedInstanceState) {

SharedPreferences preferences = this.getSharedPreferences("MyPreferences", MODE_PRIVATE);

SharedPreferences.Editor editor = preferences.edit();


super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);

if(preferences.getString("Username", "").length()<=0 || preferences.getString("loggedin_user", "").length()<=0){
    showDialog(DIALOG_LOGIN);

}

b1= (Button) this.findViewById(R.id.joinbutton);

b1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        Intent intent = new Intent(menuActivity.this, MainActivity.class);
        menuActivity.this.startActivity(intent);

        SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("loadMain", "1");
        editor.commit();
        }

});
b2= (Button) this.findViewById(R.id.searchbutton);

b2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            showDialog(DIALOG_SEARCH);
        }

    }

);





}

@Override
protected Dialog onCreateDialog(int id) {

    AlertDialog dialogDetails = null;

    switch (id) {


    case DIALOG_LOGIN:
                if(true){
....some code}


         break;
            case DIALOG_FORGET:
                if(true){
...some code
}
                break;
            case DIALOG_SEARCH:
            if(true){
                LayoutInflater inflater = LayoutInflater.from(this);
                View dialogview = inflater.inflate(R.layout.menusearch_layout, null);

                AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);

                dialogbuilder.setTitle("Where ya headed?");
                dialogbuilder.setView(dialogview);
                dialogDetails = dialogbuilder.create();
            }
    }

    return dialogDetails;
}
 @Override
    protected void onPrepareDialog(int id, Dialog dialog) {

        switch (id) {
        case DIALOG_LOGIN:
...some code
break;

case DIALOG_SEARCH:
                final AlertDialog alertDialog3 = (AlertDialog) dialog;
                final Button btnLocalsearch = (Button) alertDialog3
                        .findViewById(R.id.local_search);
                final Button btnSearch = (Button) alertDialog3
                        .findViewById(R.id.btn_search);
                final EditText txtsearch = (EditText) alertDialog3
                        .findViewById(R.id.txtsearch);

                btnSearch.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(final View v) {
                        //showDialog(DIALOG_FORGET);
                        //alertDialog3.dismiss();
                                // TODO Auto-generated method stub
                               menuActivity m = com.peekatucorp.peekatu.menuActivity.this;
                                final TabInfo tab = com.peekatucorp.peekatu.menuActivity.this.getCurrentTabInfo();
                                final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
                                // fragment.setText(characters[position]);

                                // second, you push the fragment. It becomes visible and the up button is
                                // shown
                                m.pushFragment(tab, fragment);


                            }



        });
    }

mainmenu.xml

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

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="65dp"
        android:layout_marginLeft="10dip"
        android:src="@drawable/registration_banner3"
        android:id="@+id/imageView" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Join Chat"
        android:id="@+id/joinbutton"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Search"
        android:id="@+id/searchbutton"
        android:layout_below="@+id/joinbutton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="55dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Profile"
        android:id="@+id/prfbutton"
        android:layout_below="@+id/searchbutton"
        android:layout_marginTop="72dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignLeft="@+id/searchbutton"
        android:layout_alignStart="@+id/searchbutton" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings"
        android:id="@+id/settingsbutton"
        android:layout_below="@+id/prfbutton"
        android:layout_marginTop="51dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <LinearLayout android:id="@+id/footer"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@layout/footer_repeat"
        android:layout_alignParentBottom="true">



    </LinearLayout>
</RelativeLayout>

ChatRoomsFragment.java (WORKING FRAGMENT)

public class ChatRoomsFragment extends SherlockFragment implements OnItemSelectedListener{
    String[] items;
    List<String> list;
    Spinner my_spin;
     RadioButton mainRoom;
     RadioButton customRoom;
     RadioButton GPSRoom;
     EditText privateRoom;
     EditText GPSsearch;
     TextView GPSaddress;
     String selected_public;
     Context contexxt;
     ImageLoader imageLoader;
     public AbstractTabStackNavigationActivity navact;
    @Override

      public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
          setRetainInstance(true);

          final View v = inflater.inflate(R.layout.chatrooms_layout, container, false);
          contexxt = v.getContext();
         // setRetainInstance(true);
          SharedPreferences preferences = v.getContext().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE);
          my_spin=(Spinner)v.findViewById(R.id.spinner1);
          my_spin.setOnItemSelectedListener(this);
          selected_public = preferences.getString("selected_room", "Adult Lobby");
          AsyncHttpClient  client = new AsyncHttpClient();
            RequestParams params = new RequestParams();

            GPSsearch = (EditText)v.findViewById(R.id.cr_gps_search);
            GPSaddress = (TextView)v.findViewById(R.id.cr_gps_address);
            GPSaddress.setText(preferences.getString("user_location", ""));
            Button search_go = (Button)v.findViewById(R.id.cr_go_search);
            Button address_go = (Button)v.findViewById(R.id.cr_go_address);
            Button changeroom = (Button)v.findViewById(R.id.cr_changeroom);
            //Button changeroom2 = (Button)v.findViewById(R.id.cr_changeRoom2);


    search_go.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                 MainActivity m = (MainActivity)getActivity();
                 final TabInfo tab = m.getCurrentTabInfo();
                    final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(GPSsearch.getText().toString(),"1");
                   // fragment.setText(characters[position]);

                    // second, you push the fragment. It becomes visible and the up button is
                    // shown
                    m.pushFragment(tab, fragment);  
            }
        });

Can someone please explain to me how to get it to load the fragment. Thank you. Let me know if I am leaving out any relevant code. Im getting a null pointer exception as my error.

Well, first of all, here is the code I was talking about in my comment:

 btnSearch.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(final View v) {
         menuActivity m = dialog.getOwningActivity();
         final TabInfo tab = m.getCurrentTabInfo();
         final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
         m.pushFragment(tab, fragment);
         ...

However, now that I type this up, it doesn't make sense that the NPE was on the call to pushFragment like you said. If the activity outer-class reference was really the null pointer, then it should have crashed a few lines earlier, calling getCurrentTabInfo. Thus I don't think this code change will help. Please take a second look at the stack you are seeing, and tell me what line the NPE is happening on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM