Pass values from fragment to fragment on Same Activity - android

I have a problem with passing a number from one fragment to another in the same activity , I got that number to Activity, but when I try to pass it to 2nd fragment it gives me null.
Any help is appreciated
Here is the code for the Passing and a bit more, there maybe typos as i wanted to put as little of code as I could
MainActivity
package com.example.design.ex;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import example.test.R;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.example.design.ex.fragments.ReceiptItemsFragment;
public class NewReceiptActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int num = 0;
Intent intent = getIntent();
int Broj = intent.getIntExtra("Num", num);
Bundle bundle=new Bundle();
bundle.putInt("Broj", Broj);
setContentView(R.layout.activity_test);
ReceiptItemsFragment frag = (ReceiptItemsFragment)
getSupportFragmentManager().findFragmentById(R.id.receipt);
frag.setArguments(bundle);
}
}
Fragment 1
package com.example.design.ex.fragments;
import example.test.R;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import com.actionbarsherlock.app.SherlockFragment;
public class CategoriesItemsFragment extends SherlockFragment {
int num = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_categories_items,
container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
itemsGrid.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, final View itemView, int
arg2, long arg3)
{
num = arg2 + 1;
Intent intent = new Intent(getActivity().getBaseContext(),NewReceiptActivity.class);
intent.putExtra("Num", num);
startActivity(new Intent(getActivity(), NewReceiptActivity.class));
getActivity().startActivity(intent);
}
});
}
}
Fragment 2
package example.design.ex.fragments;
import example.test.R;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
public class ReceiptItemsFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
Bundle arguments = getArguments();
if (arguments != null)
{
Log.d("ISnull","no!");
} else {
Log.d("ISnull","yes!");
}
int num=getArguments().getInt("Num");
return inflater.inflate(R.layout.fragment_receipt_items, container,
false);
}
Main Activity XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/titles"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1.5"
class="example.ex.fragments.CategoriesItemsFragment" />
<LinearLayout
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/sun_flower" >
</LinearLayout>
<fragment
android:id="#+id/receipt"
android:name="example.ex.fragments.ReceiptItemsFragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
class="example.ex.fragments.ReceiptItemsFragment" />
</LinearLayout>
Here is the Error
06-11 07:41:00.419: E/AndroidRuntime(2801): at
com.example.NewReceiptActivity.onCreate(NewReceiptActivity.java:60)
which is this line or the next if i put log (tried to get it to show me the id)
ReceiptItemsFragment frag = (ReceiptItemsFragment)
getSupportFragmentManager().findFragmentById(R.id.receipt);

Verify if frag in NewReceiptActivity is different null. Verify if Numt is 2.
Move the line in ReceiptItemsFragment:
int num=getArguments().getInt("Num"); //this should get number 2 from Frist Fragment but it gives null
from method onCreateView to onActivityCreated:
public void onActivityCreated (Bundle savedInstanceState) {
int num=getArguments().getInt("Num"); //this should get number 2 from Frist Fragment but it gives null

I think the problem is here :
ReceiptItemsFragment frag=new ReceiptItemsFragment(); //2nd fragment
frag.setArguments(bundle);
You're creating a new fragment but its not the one you've got in your layout.
try this instead :
setContentView(R.layout.activity_test); // Here is where that 2 fragments are Located
ReceiptItemsFragment frag = getFragmentManager().findFragmentById(...) //your fragment id
frag.setArguments(bundle);
so you don't create a new fragment but reference the one you've got in your layout.
Hope that helps.

You can create a subclass of Application and store the object there. Check this.
Or you can use static variables in the activity class.

I went on different approach using Interface on passing data,As explained here
https://stackoverflow.com/a/12311939/1393695
And got it working, I want to thank everybody here for the help.
The problem was that I was looking at fragments as they where activities.

Related

The activity is showing blank when it is opened from the Fragment Class

I have a fragment activity which is a listview. When the user clicks the an item from the listview it opens another activity. The new activity is loaded but shows as blank.
I have tried to recreate the activity but it does not solve the problem. I am comparatively new to Android and Java Coding. The app works fine. I can use the back button to go back to the list and click another item. The result is the same.
I tried everything possible but unable to fix it. Can some one help me on this?
Fragment Activity
package com.ornisoft.bloodbankapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ornisoft.bloodbankapp.DataAdapter.MessageDataAdapter;
import com.ornisoft.bloodbankapp.DataModel.MessageDataModel;
import java.util.ArrayList;
public class MessageFragment extends Fragment {
DatabaseHelper db;
ArrayList<MessageDataModel> MessageDataModelArrayList;
MessageDataAdapter MessageDataAdapter;
Context context;
ListView lvMessages;
public MessageFragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listview_message, container, false);
context = container.getContext();
lvMessages = view.findViewById(R.id.lvMessages);
lvMessages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), MessageActivity.class);
//intent.putExtra("id",l);
startActivity(intent);
}
});
db = new DatabaseHelper(context);
loadMessages();
return view;
}
public void loadMessages(){
MessageDataModelArrayList = db.getMessages();
MessageDataAdapter = new MessageDataAdapter(context,MessageDataModelArrayList);
lvMessages.setAdapter(MessageDataAdapter);
MessageDataAdapter.notifyDataSetChanged();
}
}
Message Activity
package com.ornisoft.bloodbankapp;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MessageActivity extends AppCompatActivity {
DatabaseHelper db;
int messageID;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_message);
db = new DatabaseHelper(this);
Toast.makeText(MessageActivity.this, "Hello world " , Toast.LENGTH_SHORT).show();
/*messageID= Integer.parseInt(getIntent().getStringExtra("id"));
MessageModel messageModel = db.getMessage(messageID);*/
}
}
Layout
<?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=".MessageActivity">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you
I found the error. I am using the wrong create class on the MessageActivity.
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState)
when I changed it to
protected void onCreate(Bundle savedInstanceState)
the problem is solved and it works perfect.
Thank you all.

App Crashes While Trasitioning One Fragment To Another

I am trying to jump from one fragment to another fragment. But whenever i click the button to jump on second fragment my app crashes.
Here are my source files. Please help !
I want to Navigate Tab1 to AlertScreen.
Here is Tab1.java
package com.example.bavarian.sos;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class Tab1 extends Fragment {
ImageButton HelpButton ;
private boolean playing = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
HelpButton = (ImageButton) rootView.findViewById(R.id.imageButton);
final MediaPlayer Alarm = MediaPlayer.create(getContext(),R.raw.sound);
//private boolean playing = false ;
HelpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AlertScreen();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return rootView ;
}
}
AlertScreen.java
package com.example.bavarian.sos;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AlertScreen extends Fragment {
public AlertScreen(){
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alert_screen,container,false);
return rootView;
}
}
alert_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Alerrt Screen"
android:id="#+id/alerttext"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="176dp" />
</RelativeLayout>
What i am missing here ???

Android Picasso Fragment Pic from URL

I've got problem to load pic from URL do my fragment by Picasso.
When I start app it's start without any errors but pic is not loading.
My app has one MainActivity and three fragments. Below I paste xml of mainlayout and one fragment class. The best for me is this scenario:
when user click button on fragment three(red on image), pic will load from url to imageView which is located on fragment two (yellow on image) above of fragment three.
Please help
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasadown extends Fragment {
private klasadownlistener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentdown, container, false);
ImageView img = (ImageView) view.findViewById(R.id.imgVV);
Context c = getActivity().getApplicationContext();
Picasso.with(c).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.fit().into(img);
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMenu:
updateText("Menu");
SetImage();
break;
case R.id.btnKontakt:
updateText("Kontakt");
break;
default:
break;
}
}
};
Button btnMenu = (Button) view.findViewById(R.id.btnMenu);
Button btnKontakt = (Button) view.findViewById(R.id.btnKontakt);
btnKontakt.setOnClickListener(clickListener);
btnMenu.setOnClickListener(clickListener);
return view;
}
public interface klasadownlistener {
public void onItemSelected(String txt);
}
private void updateText(String txt) {
listener.onItemSelected(txt);
}
public void SetImage() {
ImageView img = (ImageView) getView().findViewById(R.id.imgVV);
Picasso.with(getActivity().getApplicationContext()).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").into(img);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof klasadownlistener) {
listener = (klasadownlistener) activity;
} else {
throw new ClassCastException(activity.toString() + " musi implementowa� interfejs: OverviewFragment.OverviewFragmentActivityListener");
}
}
}
<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"
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=".MainActivity">
<fragment
android:id="#+id/fragmentup"
class="testowy.com.testowyfragment2.Klasaup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
</fragment>
<fragment
android:id="#+id/fragmentcenter"
class="testowy.com.testowyfragment2.Klasacenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
<fragment
android:id="#+id/fragmetdown"
class="testowy.com.testowyfragment2.Klasadown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
</LinearLayout>
package testowy.com.testowyfragment2;
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;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasacenter extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragmentcenter, container, false);
return view;
}
public void SetText(String txt){
TextView view = (TextView) getView().findViewById(R.id.fragmentcenterText);
view.setText(txt);
}
}
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends Activity implements Klasadown.klasadownlistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String txt) {
Klasacenter fragment = (Klasacenter) getFragmentManager()
.findFragmentById(R.id.fragmentcenter);
// sprawdzamy czy fragment istnieje w tej aktywno�ci
if (fragment != null && fragment.isInLayout()) {
// ustawiamy teskt we fragmencie
fragment.SetText(txt);
ImageView img = (ImageView) findViewById(R.id.imgV);
Picasso.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").fit().into(img);
}
}
}
It's stupid to say but I forget to add internet permission:)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
now everything is ok!

Drawer menu view requires 2 clicks

A repo with example: https://bitbucket.org/troffel/drawer-button-error
I've come across an issue I can't for the life of me figure out. From a much larger project I was able to deduce it into a smaller dummy project.
Problem:
When the app launches, the buttons in the drawer menu works correctly. However, after changing orientation one or more times the buttons all of a sudden require two key presses.
When logging out events, it shows that the eventlistener connected to the clicked views is triggered, however nothing seem to happen on first click.
I added the main files to the post, repo so you can replicate it if interested.
Any help is much appreciated.
Main layout:
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/background_light">
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
layout of initial fragment(category_fragment):
<ListView
android:id="#+id/left_drawer_listview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:choiceMode="singleChoice"/>
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#ecebec"/>
<TextView
android:id="#+id/drawer_settings"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#android:color/black"
android:textSize="20sp"
android:clickable="true"
android:onClick="openSettings"
android:gravity="center_vertical"
android:text="Settings"
android:paddingLeft="10sp"/>
</LinearLayout>
fragment that replaces the initial(preffragment):
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/settings_checkbox_container"
android:layout_weight="1">
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/settings_back"
android:text="Save"
android:layout_weight="1"/>
</LinearLayout>
Mainactivity:
package com.example.testdrawer;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.left_drawer, new CategoryFragment());
fragmentTransaction.commit();
}
public void openSettings(View v){
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction ftrans = fmanager.beginTransaction();
PrefFragment prefFragment = new PrefFragment();
ftrans.replace(R.id.left_drawer, prefFragment);
ftrans.commit();
Log.i("test", "Opening settings");
}
}
categoryfragment code:
package com.example.testdrawer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CategoryFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.category_fragment, container, false);
//drawer menu
return v;
}
}
Preffragment.java:
package com.example.testdrawer;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class PrefFragment extends Fragment{
private Context context;
private View checkbox_container;
private Button settingsBack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.preffragment, container, false);
checkbox_container = v;
settingsBack = (Button) v.findViewById(R.id.settings_back);
settingsBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//setupSimplePreferencesScreen();
return v;
}
public void saveSettings(){
//setSettings(checkbox_container);
FragmentManager fmanager = getFragmentManager();
FragmentTransaction ftrans = fmanager.beginTransaction();
ftrans.replace(R.id.left_drawer, new CategoryFragment());
ftrans.commit();
Log.i("test", "saving settings");
}
}
OK! This is super weird, but I found the problem.
Using replace(container, fragment) instead of add(container, fragment) in my solved the issue.
The problem was that I was calling add(container, fragment) in my activitys onCreate method. This meant that when an orientation change happened, it would call add(container, fragment) on top of the already existing one.
replace(container, fragment) works because it, logically, replaces the existing one.
A solution that includes using add(container, fragment) would be to have remove(fragment) in my activitys onDestroy method, thus avoiding doable drawing.
Hope it saves someone else some time!

Moving from one fragment to another in a custom listview in android

I have created a navigation drawer for my app from androidhive.info. In that navigation drawer, in one fragment, I have created a custom listview which shows the elements with a name and image. Now upon clicking an item of the custom listview, I need to show the details of the clicked list element. For that I have created another fragment. Now upon clicking the listview element, I should move onto the details of the selected element. The code which I have used for moving from one fragment to another is this:
Fragment fragment=new ImportantNumbersFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
But the getSupportFragmentManager() is showing an error in eclipse like this: The method getSupportFragmentManager() is undefined for the type PagesFragment. This is the code of my custom listview fragment.
PagesFragment.class
public class PagesFragment extends ListFragment implements OnItemClickListener{
Typeface tf;
ListView lv;
List<SimpleRow>rowItems;
public PagesFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
Helper help=new Helper(getActivity().getApplicationContext());
String choice1="സര്‍ക്കാര്‍ സ്ഥാപനങ്ങള്‍";
String choice1new=help.changemalayalam(new Data(choice1));
String choice2="പത്രം";
String choice2new=help.changemalayalam(new Data(choice2));
String choice3="ന്യൂസ് ചാനല്‍";
String choice3new=help.changemalayalam(new Data(choice3));
String choice4="യൂണിവേഴ്സിറ്റികള്‍";
String choice4new=help.changemalayalam(new Data(choice4));
String choice5="പഞ്ചായത്ത് ഓഫീസ്";
String choice5new=help.changemalayalam(new Data(choice5));
String choice6="ഇന്‍ഷുറന്‍സ്";
String choice6new=help.changemalayalam(new Data(choice6));
String choice7="പോലീസ് സ്റ്റേഷന്‍";
String choice7new=help.changemalayalam(new Data(choice7));
String choice8="ഫയര്‍ സ്റ്റേഷന്‍";
String choice8new=help.changemalayalam(new Data(choice8));
ArrayList<String>choice=new ArrayList<String>();
choice.add(choice1new);
choice.add(choice2new);
choice.add(choice3new);
choice.add(choice4new);
choice.add(choice5new);
choice.add(choice6new);
choice.add(choice7new);
choice.add(choice8new);
lv=(ListView)rootView.findViewById(R.id.list1);
rowItems=new ArrayList<SimpleRow>();
for (int i = 0; i < choice.size(); i++) {
SimpleRow item = new SimpleRow(choice.get(i));
rowItems.add(item);
CustomSimpleListAdapter adapter = new CustomSimpleListAdapter(getActivity().getApplicationContext(),R.layout.list_single, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(getActivity().getApplicationContext(), "You clicked on position "+position,Toast.LENGTH_LONG).show();
//Here upon clicking the list element, I need to go to ImportantNubersFragment
Fragment fragment=new ImportantNumbersFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getActivity().getApplicationContext(), "You clicked on position "+arg2,Toast.LENGTH_LONG).show();
}
}
ImportantNumbersFragment.class
public class ImportantNumbersFragment extends Fragment {
public ImportantNumbersFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_container, container, false);
return rootView;
}
}
fragment_important_numbers.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout android:name="fragments.YourInitialFragment"
android:id="#+id/fragment_container"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" />
</LinearLayout>
I want to move from PagesFragment to ImportantNumbersFragment upon clicking the list element in the custom listview. So in the OnListItemClick, I have given the code for moving from fragment to another. I have to do this in the sameway as that of moving from one activity to another activity using intents like:
Intent i=new Intent(First.this,Second.class);
startActivity(i);.
Since I'm new to fragments, I don't know how this can be achieved in fragments. That's why I have asked here. Can someone please point out the errors in this code. Thanks in advance..
Are you using Support package for fragment in all extended Fragment
Classes, Check !
.
I myself have used the code from AndroidHive and it works perfectly
.
There it does not uses Support package for extended fragment classes
.
Somewhere in code you are using a Support import, Make sure you
maintain uniformity among imports
.
Programatically Speaking for ex::
If you are using support package use codes like these
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
If you are not using support package use codes imports ::
import android.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.app.FragmentActivity;
import android.app.FragmentTransaction;
import android.widget.DrawerLayout;
{EDIT - Sample on how one of the way to perform fragment transaction}
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class MainActivity extends FragmentActivity {
Fragment fragment;
String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("MainActivity", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Store the name of the class
className=MainActivity.class.getSimpleName();
//First fragment should be mounted on oncreate of main activity
if (savedInstanceState == null) {
/*fragment=FragmentOne.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(className).commit();
*/
Fragment newFragment = FragmentOne.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).addToBackStack(null).commit();
Log.d("FRAGMENT-A", "fragment added to backstack");
}
}
}
FragmentOne.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.sample.screennavigation.UtilRangeSeekBar.OnRangeSeekBarChangeListener;
public class FragmentOne extends Fragment{
//Declare variables that hold the data for configuration change
public static FragmentOne newInstance(){
Log.d("FragmentOne", "newInstance");
FragmentOne fragment = new FragmentOne();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FragmentOne", "onCreateView");
View view=inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
{EDIT-2}
PagesFragment ... is using a support package somewhere, check
it !
Check imports of pagefragment
But the getSupportFragmentManager() is showing an error in eclipse like this: The method getSupportFragmentManager() is undefined for the type PagesFragment.
Error in your code clearly says you are using a supportpackage import
and it is conflicting the execution
Rememmber you cannot mix the imports
Hope it helps !, let me know if you need any additional info

Categories

Resources