How to send data from fragment to fragment? - java

I have 1 layout. It contains 2 fragments. There are 2 buttons in this layout. When I clicked button 1, the fragment 1 is going to display. I am going to click button in fragment 1 content of textview display "welcome" then i click button 2 in main layout, fragment 2 is going to display and textview of fragment 2 is going to display content of textview of fragment 1.
Here This is my code.Please show and give me some comment for me.How to reslove this issue
The first is mainlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment1" />
<Button
android:id="#+id/btnFragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment2" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/container">
</LinearLayout>
The first is fragment1.xml
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
The first is fragment1.java
public class Fragment1 extends Fragment{
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = null;
view = inflater.inflate(R.layout.fragment1, null);
//I will get text after I press button and using bundle for storage
and send send to fragment
return view;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}}
The first is fragment2.xml
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
The first is fragment2.java
public class Fragment2 extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2, null);
//In this I am going to using Bundle to get message from fragment1
}}
The first is MainActivity.java
public class MainActivity extends FragmentActivity {
Button btnFragment1, btnFragment2;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = getSupportFragmentManager();
btnFragment1 = (Button) findViewById(R.id.btnFragment1);
btnFragment1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, new Fragment1(), "TAG_FRAGMENT1");
transaction.addToBackStack(null);
transaction.commit();
}
});
btnFragment2 = (Button) findViewById(R.id.btnFragment2);
btnFragment2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, new Fragment2(), "TAG_FRAGMENT2");
transaction.addToBackStack(null);
transaction.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}

Use a interface as a call back to the activity and then communicate the data to fragment2
http://developer.android.com/training/basics/fragments/communicating.html
There is a Example in the above link

#Raghunandan has a good answer. Not the only option though, you could use a BroadcastManager or LocalBroadcastManager. This way you can easily respond to events across Activities, Fragments, Services, etc.
how to use LocalBroadcastManager?

You can use Activity as a proxy between fragments this is how you can inform Activity about event in fragment:
public class FragmentA extends Fragment {
OnSomethingDoneInFragmentListener mListener;
//this inteface must implement Activity that use the fragment
public interface OnSomethingDoneInFragmentListener {
public void onSomethingDone(Object someObject);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnSomethingDoneInFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnSomethingDoneInFragmentListener");
}
}
}

Try to use EventBus, it saves you a lot of work.
EventBus is an Android optimized publish/subscribe event bus. A
typical use case for Android apps is gluing Activities, Fragments, and
background threads together. Conventional wiring of those elements
often introduces complex and error-prone dependencies and life cycle
issues. With EventBus propagating listeners through all participants
(e.g. background service -> activity -> multiple fragments or helper
classes) becomes deprecated. EventBus decouples event senders and
receivers and thus simplifies communication between app components.
Less code, better quality. And you don't need to implement a single
interface!
Define your event, which is a data object:
class MyClickEvent {
// ...
public MyClickEvent(String field1, int field2) {
// ...
}
}
In a Fragment, register itself to handle event:
class MyFragment extends Fragment {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
EventBus.getDefault().register(this, MyClickEvent.class);
}
public void onEvent(MyClickEvent event) {
// handle the event
}
}
Post event on button click:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post(new MyClickEvent("Some data", 123456));
}
});

Related

OnClickListener() crash in Fragment

For some reason, when I click on the Toolbar(toolbar) and Float button(button) in my app, the OnClickListener () method crashes the snippet and app
Although the ImageButton(OnOff) handler runs and does not crash the fragment
Fragment
public class ZnonkiFragment extends Fragment {
private SharedPreferences settings;
private ImageButton OnOff;
private ViewPager viewPager;
private DrawerLayout drawerLayout;
private MainActivity.PagerAdapter pagerAdapter;
private FloatingActionButton button;
final Context context = getActivity();
private androidx.appcompat.widget.Toolbar toolbar;
private TabLayout tabLayout;
private String ZvonOne, ZvonTwo;
private List<Fragment> list = new ArrayList<>();
private String url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_znonki, container,
toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.menu));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
}
});
//...
addListenerOnButton(view);
return view;
}
public boolean checkString(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
public void addListenerOnButton (final View viewOne){
OnOff = viewOne.findViewById(R.id.onOff);
button = viewOne.findViewById(R.id.floatingActionButton);
OnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//...
});
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
//...
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//...
});
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ZnonkiFragment">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="Звонки"
app:titleTextColor="#FFFFFF" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:clickable="true"
android:focusable="true"
app:backgroundTint="#color/colorAccent"
app:backgroundTintMode="src_atop"
app:srcCompat="#drawable/kek" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:isScrollContainer="true"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="6dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#E6E6FA">
</com.google.android.material.tabs.TabLayout>
<ImageButton
android:layout_margin="16dp"
android:id="#+id/onOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#null"
app:srcCompat="#drawable/on" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/rager"
android:layout_width="match_parent"
android:layout_height="557dp"
android:layout_marginTop="105dp"
/>
</FrameLayout>
Although this code worked in the main activiti
I don't know why but there are no errors in debug mode
What Kundan has suggested is correct but the fix is much easier.
You don't need this:
final Context context = getActivity();
If you need to gain access to the context in a Fragment you can call requireContext() if you need access to the Activity you can call requireActivity()
So your toast message can become:
Toast.makeText(requireContext(),"lel",Toast.LENGTH_LONG).show();
I think main cause of this issue is
final Context context = getActivity();
which is used in
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
}
});
please note the getActivity() method returns the current activity with which this fragment is attached. and you are calling while the fragment object is creating before it is attached to activity.
you can change the above code to :
Context context;
and override the method as
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
Hope this answers your question.
The solution is simple
In your fragment class file, dont create custom function for calling click events rather you can use the android's defaul method by simply implementing them in your class file and then override it. Thats makes the code more simpler and reusable in future.
public class ZnonkiFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private SharedPreferences settings;
private ImageButton OnOff;
private ViewPager viewPager;
private DrawerLayout drawerLayout;
private FloatingActionButton button;
final Context context = getActivity();
private TabLayout tabLayout;
private String ZvonOne, ZvonTwo;
private List<Fragment> list = new ArrayList<>();
private String url;
private Toolbar mToolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_znonki, container, false);
mToolbar = view.findViewById(R.id.toolbar);
mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_launcher_background));
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "lel", Toast.LENGTH_LONG).show();
}
});
//...
OnOff = view.findViewById(R.id.onOff);
OnOff.setOnClickListener(this);
OnOff.setOnLongClickListener(this);
button = view.findViewById(R.id.floatingActionButton);
return view;
}
public boolean checkString(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.onOff:
//call your onclick function here...
break;
case R.id.floatingActionButton:
//call your onclick function here...
break;
}
}
#Override
public boolean onLongClick(View view) {
switch (view.getId()) {
case R.id.floatingActionButton:
//call your long click function here...
break;
}
return false;
}
}
I have left comments on particular Loc where you can add your code and check it. And the toolbar was crashing due to improper importing of the libraries. If you havent used the androidx library into your gradle file then you can go with simple toolbar which is of "import android.support.v7.widget.Toolbar". This will surely stop your onclick crash on toolbar.
If there is any issue, just let me know. Thank you.

Making userInput from main activity to display on second activity in Android

I've seen a few related topics on here but after many attempts I just couldn't seem to find the solution so hopefully someone out there can help. Here's my code so far (Trying to make userInput appear on the 2nd activity as the result):
MainActivity.java
package winfield.joe.wind.v1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.userInput);
}
//Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property
public void calc(View view) {
RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);
if (text.getText().length() == 0) {
// if the text field is empty show the message "enter a valid number" via toast message
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
} else {
int userInput = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("userInput", userInput);
startActivityForResult(i, 0);
startActivity(i);
// parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (toKilometers.isChecked()) {
text.setText(String.valueOf(convertToKM(inputValue)));
// uncheck "to km" Button
toKilometers.setChecked(false);
// check "to knots" Button
toKnots.setChecked(true);
} else { /* if toKnots button isChecked() */
text.setText(String.valueOf(convertToKnots(inputValue)));
// uncheck "to knots" Button
toKnots.setChecked(false);
// check "to km" Button
toKilometers.setChecked(true);
}
}
}
/*private void putExtra(String string, int result) {
// TODO Auto-generated method stub
}*/
private double convertToKM(double inputValue) {
// convert knots to km
return (inputValue * 1.8);
}
private double convertToKnots(double inputValue) {
// convert km to knots
return (inputValue * 0.539956803);
}
}
SecondActivity.java
package winfield.joe.wind.v1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
Intent i = getIntent();
String userInput = i.getStringExtra("userInput");
}
//onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
public void GoBack(View view) {
//AlertDialog appears upon the onclick of the go back button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
// set dialog message
builder .setCancelable(false)
.setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to Main Activity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
})
.setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the home page
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
})
.setNegativeButton("View Results",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical">
<!--TITLE-->
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="22dp"
android:gravity="center"
android:text="#string/titleMain"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="30sp" />
<!--USER-INPUT-->
<EditText
android:id="#+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="#+string/userInput"
android:inputType="numberDecimal"
android:paddingEnd="40dp"
android:paddingStart="20dp"
android:paddingTop="30dp" >
<requestFocus />
</EditText>
<!--TWO RADIO BUTTONS-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!--toKNOTS-->
<RadioButton
android:id="#+id/toKnots"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.04"
android:checked="true"
android:text="#string/toKnots" />
<!--toKM-->
<RadioButton
android:id="#+id/toKilometers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp"
android:text="#string/toKilometers" />
</LinearLayout>
<!--CALCULATE-->
<Button
android:id="#+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:onClick="calc"
android:text="#string/calc" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<!-- TITLE -->
<TextView
android:id="#+id/titleResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="#string/titleResults"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="25sp" />
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/result"
android:textColorHint="#color/textColor" >
<requestFocus />
</TextView>
<Button
android:id="#+id/GoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/GoBack"
android:onClick="GoBack" />
</LinearLayout>
Change this...
int userInput = R.string.userInput;
...to...
String userInput = text.getText().toString();
Everything in the R.java file is a static final int which is used to reference a resource - it isn't actually the resource itself (or the contents of the resource in the case of an EditText for example).
**This is the correct way to change information between 2 activity, of corse be careful to activity lifecycle. This code best practice!**
First activity
public class MainActivity extends Activity {
private static final String Tag = "ACTIVITY";
private static final String CONTATORE = "contatore";
TextView et;
Button btn,btnLancia;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (TextView) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btn);
btnLancia = (Button) findViewById(R.id.btnLancia);
if(savedInstanceState != null){
counter = savedInstanceState.getInt(CONTATORE);
}
btnLancia.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanciaActivity();
}
});
et.setText("" + counter);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
++counter;
et.setText("" + counter);
}
});
Log.d(Tag, "OnCreate");
}
protected void lanciaActivity() {
Intent intent = new Intent(this,Activity2.class);
Bundle bundle = new Bundle();
bundle.putInt(Activity2.VALUE, counter);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(CONTATORE, counter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
SECONd ACTIVITY
public class Activity2 extends Activity {
private static final String Tag = "ACTIVITY2";
public static final String VALUE = "value";
private static final String VALOREATT = "val";
TextView contatore;
Button button;
int contatoreq;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
Log.d(Tag, "OnCreate");
contatore = (TextView) findViewById(R.id.textView1);
button = (Button) findViewById(R.id.btnDoppio);
if(savedInstanceState!=null){
contatoreq = savedInstanceState.getInt(VALOREATT);
}
else {
Intent intetn = getIntent();
Bundle bundle = intetn.getExtras();
if(bundle!=null)
contatoreq = bundle.getInt(VALUE);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
contatoreq = contatoreq*2;
contatore.setText("" + contatoreq);
}
});
contatore.setText("" + contatoreq);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(VALOREATT, contatoreq);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
I see two problems in your code.
First you are setting userInput to R.string.userInput which is kind of strange imo. You should set userInput to the text from the TextField:
String userInput = text.getText().toString();
The second problem I notice is that you start the second intent twice. Once for result and once without:
startActivityForResult(i, 0);
startActivity();
Try to remove the startActivityForResult if you do not want to work with the result from the last activity. You probably misunderstood was startActivityForResult(i, 0) does.
You basically call startActivityForResult() if you want to get the result back from the activity. For example you are in your MainActivity and want to display a photo in there. Now you can start the camera intent with startActivityForResult() and after the photo is taken you can process this in your MainActivity.
If you just want to pass the value to the next activity a simple startActivity() is enough. Here is the link to the docs if you want to read more about this topic:
startActivityForResult() - Documentation

hi i have a list view that contains list of elements i want to use onitemclick method to open another list

hi i have a list view that contains list of methods so here i am going to display it's
parameters in another list so when i click on list item(method) it has to display it's
parameter it can achieved through onitemclick() method i tried but it shows some error
can any one help please
this is my listview.java file
public class Listview extends Activity{
private CursorAdapter customAdapter;
private Param databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
private static final String TAG = Listview.class.getSimpleName();
private ListView lv;
public static ArrayList<String> your_array_list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
databaseHelper = new Param(this);
customAdapter = new CursorAdapter (this, databaseHelper.getTripList( Param.DESC),
0);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
Log.d(TAG, "clicked on item: " + position);
}
});
lv = (ListView) findViewById(R.id.listView1);
Button backButton=(Button)findViewById(R.id.methodbackbutton1);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Listview.this.finish();
}
});}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, your_array_list );
lv.setAdapter(arrayAdapter);
try {
DisplayM.main();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed()
{
Intent intent3 = new Intent(this, Nextactivity.class);
startActivity(intent3);
finish();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
}
this is my listview.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewMyRecording"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/listofMethods"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView1"
android:layout_width="wrap_content"
android:layout_height="384dp" >
</ListView>
<Button
android:id="#+id/methodbackbutton1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:onClick="onBackPressed"
android:text="#string/Backtopreviousscreen" />
</LinearLayout>
You are taking the reference of Same ListView resource findViewById(R.id.listView1) in both variable listView & lv.
Second thing, why you are taking Cursor Adapter for your list?
Third thing, what's the purpose of DisplayM.main();
Fourth thing, you can finish an activity by writing just finish() then why you are writing it like Listview.this.finish(); ?

Android IllegalStateException: Fragment not attached to Activity webview

So I'm new to android app writing, and I am trying to work on a practice app that I can hopefully turn into something later. I had 3 tabs in the actionbar that ran fine before I decided to try to add webview to one of them. Now it crashes with an IllegalStateException. And since I don't know too much about android at the moment, I can't seem to figure out what is wrong.
The main activity:
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Web", "Facebook", "Twitter" };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs)
{
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
}
The WebFragment with the webview:
public class WebFragment extends Fragment
{
private String url = getString(R.string.website);
//#Override
//public void onActivityCreated(Bundle savedInstanceState)
//{
//super.onActivityCreated(savedInstanceState);
//}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.web_fragment, container, false);
WebView tolerableWebView = (WebView) getView().findViewById(R.id.webview);
tolerableWebView.getSettings().setJavaScriptEnabled(true);
tolerableWebView.loadUrl(url);
return rootView;
}
}
the TabsPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter
{
public TabsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int index)
{
switch (index) {
case 0:
// Top Rated fragment activity
return new WebFragment();
case 1:
// Games fragment activity
return new FacebookFragment();
case 2:
// Movies fragment activity
return new TwitterFragment();
}
return null;
}
#Override
public int getCount()
{
// get item count - equal to number of tabs
return 3;
}
}
The webfragment xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</WebView>
The main activity xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Any help would be great! Thanks
Generally you get that error when you try to perform work after the Fragment is no longer attached to the Activity. In the callback that triggers the IllegalStateException add a check for isAdded: http://developer.android.com/reference/android/app/Fragment.html#isAdded()
if(!isAdded()) {
return;
}

View controls remain after listfragment is replaced by nested fragment

I have a tabbed view activity with 3 tabs and one fragment in each tab. Those fragments are managed by a FragmentPageAdapter linked to a viewpager.
Everything works fine until I try to have a 4th fragment (ServiceSpecifNotListFragment) that would be a nested fragment of one of the fragments (ServicesListFragment) managed by the FragmentPageAdapter.
When I try to replace the ServicesListFragment by the ServiceSpecifNotListFragment. I manage to replace only the list element from ServicesListFragment by the ServiceSpecifNotListFragment, the other view controller (a button) from ServicesListFragment remains....
I have been wondering if the problem lies in the fact that the method I use to replace the fragment by its subfragment is transaction.replace(R.id.service_list_fragment, newFragment).commit(); and service_list_fragment is the id of the listfragment main linear layout which contains the listview defined with the id: #id/android:list
The closest Q&A I found to this was this one but as far as I understood I am using the fragment container id correctly.
Here is the code and layout:
Layout of ServicesListFragment (the parent of the nested fragment)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/service_list_fragment">
<Button
android:id="#+id/addServiceButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="AddService" />
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</LinearLayout>
Layout of ServiceSpecifNotListFragment(the fragment to be nested)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/service_notif_list_fragment" >
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</LinearLayout>
Main activity xml layout (it is basically a reference to the pager):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
Source code of ServiceListFragment, the call for the nesting of fragments is in the onListItemClick :
public class ServicesListFragment extends ListFragment {
private final String TAG = "ServicesListFragment";
Button addButton = null;
ServiceNotifRowAdapter adapter;
ArrayList<NotifService> list = new ArrayList<NotifService>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity parent = getActivity();
// some ommited code for populating adapter with list of stored subscriptions
adapter = new ServiceNotifRowAdapter(getActivity().getApplicationContext(),list);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.servicelist_fragment, container, false);
addButton = (Button) rootView.findViewById(R.id.addServiceButton);
MainActivity m = (MainActivity) getActivity();
addButton.setOnClickListener(m);
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
NotifService item = (NotifService) getListAdapter().getItem(position);
Log.d(TAG, "selected service " + item.getServiceURI());
Fragment newFragment = new ServiceSpecifNotListFragment();
Bundle bundle = new Bundle();
bundle.putString("service", item.getServiceURI());
newFragment.setArguments(bundle);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.service_list_fragment, newFragment).commit();
}
Main activity java code
public class MainActivity extends FragmentActivity implements TabListener, AddServiceDialogFragmentListener
, OnClickListener{
private final String TAG = "MQTT main activity";
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, StatusListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ServicesListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ConfigFragment.class.getName()));
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : MqttApplication.tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// lock the screen in portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
Tabs page adapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
private FragmentManager fm;
private final String TAG = "TabsPagerAdapter";
public TabsPagerAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fm = fm;
this.fragments = fragments;
}
#Override
public Fragment getItem(int index) {
return this.fragments.get(index);
}
#Override
public int getCount() {
return this.fragments.size();
}
// 0 - Status, 1 Service, 2 Config (due to the order in which they have been added)
public Fragment findFragmentByPosition(int position) {
return fm.findFragmentByTag(
"android:switcher:" + R.id.pager + ":"
+ this.getItemId(position));
}
}
Just an alternate solution : implemented callbacks in your code and asked your view pager to load SpecificListNotFragment when item clicked in ServiceListFragment. Have a look and try it!
public class ServicesListFragment extends ListFragment {
private final String TAG = "ServicesListFragment";
Button addButton = null;
ServiceNotifRowAdapter adapter;
ArrayList<NotifService> list = new ArrayList<NotifService>();
private onListItemClickCallbackListener mCallback;
public interface onListItemClickCallbackListener {
public void replaceFragmentToServiveListNot();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity parent = getActivity();
mCallback = parent; // remember to imlement onListItemClickCallbackListener in activity else it will give error
// some ommited code for populating adapter with list of stored subscriptions
adapter = new ServiceNotifRowAdapter(getActivity().getApplicationContext(),list);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.servicelist_fragment, container, false);
addButton = (Button) rootView.findViewById(R.id.addServiceButton);
MainActivity m = (MainActivity) getActivity();
addButton.setOnClickListener(m);
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
NotifService item = (NotifService) getListAdapter().getItem(position);
Log.d(TAG, "selected service " + item.getServiceURI());
mCallback.replaceFragmentToServiveListNot();
}
}
public class MainActivity extends FragmentActivity implements TabListener, AddServiceDialogFragmentListener
, OnClickListener,onListItemClickCallbackListener {
private final String TAG = "MQTT main activity";
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
List<Fragment> fragments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, StatusListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ServicesListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ConfigFragment.class.getName()));
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : MqttApplication.tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// lock the screen in portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void replaceFragmentToServiveListNot() {
fragments.removeAll(fragments);
fragments.add(Fragment.instantiate(this, StatusListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ServiceSpecifNotListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ConfigFragment.class.getName()));
mAdapter.notifyDataSetChanged();
}
}

Categories

Resources