Not able to set text of textview from other activity - android

i have main activity:
public class MainActivity extends AppCompatActivity {
Button btnadd;
int a1 = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SecondAct sa = new SecondAct();
sa.ttl(a1);
}
});
}
}
and i have other activity:
public class SecondAct extends Activity {
public TextView txt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
txt2 = (TextView) findViewById(R.id.txt2);
}
public void numsum(int no)
{
txt2.setText(String.valueOf(no));
}
}
activity_main.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"
>
<Button
android:id="#+id/btnadd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="addd"></Button>
<LinearLayout
android:layout_below="#+id/btnadd"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/second"></include>
</LinearLayout>
</RelativeLayout>
When i click on button from main activity to set textview text of second activity then it gives me error.
Error:
FATAL EXCEPTION: main
Process: com.example.sumdemo, PID: 13809
java.lang.NullPointerException
at com.example.sumdemo.MainActivity$1.onClick(MainActivity.java:28)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
How can i set second activity value from main activity without passing data through intent ?

final SecondAct sa = new SecondAct();
sa.ttl(a1);
never use the new operator on a class that extends Activity. You have to use startActivity to start SecondAct, and provide additional info through the Intent object

Use Application class with a static parameter.
That is
class MyApp extends Application{
public static TextView tv;
}
in the first activity:
usemyapp.tv = (TextView) findViewById(...);
in oreder to have an access from somewhere use this:
if (MyApp.tv != null)
MyApp.tv.setText("a new text");
do not forget to wrap it in mainUiThread by using a handler.
in AndroidMainfest.xml file use this:
<application
android:name=".MyApp" <<<<<<<<<<<<<<<<<<<<<<<this the name of the class
>
Futhermore, do not create an activity class by a constructor. this is a very very bad idea:) You have this error because you have created the class but onCreate() method has not called and has not attached to Android UI process.

Use this question as guide.
How to manage `startActivityForResult` on Android?
And don't try to change one activity content from another activity.

When you create an Activity object through its constructor, you can't call its life cycle methods (e.g onCreate) so your activity doesn't have a View and you can't access your views. you must use startActivity and let android handle creating Activity object and call its life cycle method. you should change its view after inflating view. for your case, you can pass extra data via Intents and use that data in your second Activity

Related

Hide/Show Button in Fragment from Activity

i am trying to hide/show Button in fragment from Activity but it give me following exception.
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Home Activity
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
CategoryFragment frag=(CategoryFragment) activity.getSupportFragmentManager()
.findFragmentByTag("cat_frag");
Button newDesigns= (Button) frag.getView().findViewById(R.id.new_designs);
newDesigns.setVisibility(View.VISIBLE);
}
}
Category Fragment
public class CategoryFragment extends Fragment{
Button newDesigns;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_category, null);
newDesigns= (Button) v.findViewById(R.id.new_designs);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCCCCC">
<TextView
android:id="#+id/list_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_logo_bg"
android:gravity="center"
android:padding="5dp"
android:textColor="#android:color/white"
android:textSize="18sp" />
<Button
android:id="#+id/new_designs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/list_name"
android:background="#color/edit_button_color"
android:padding="10dp"
android:text="#string/new_designs"
android:textColor="#color/btn_text_color"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:visibility="gone"
/>
</RelativeLayout>
Code is too large to be posted here. Thats why i have only posted the code where i am finding an issue.
I am able to get newDesigns BUTTON instance.What is shocking for me is if try to play with button instance (VISIBLE/GONE) it gives me above mentioned exception.
Help is appreciated.
You shouldn't play with a view of the Fragment while you are in a Activity directly. You will not know what the view's state will be and this can potentially lead to issues you can't even think of(beleive me i faced many). To interact with the activity's views, make an interface:
public interface AccessFragmentViews{
public void setVisibilityForButton(boolean bool);
//any other methods that you need
}
Now implement this inside the fragment class and override the method.
class YourFragment implements AccessFragmentViews{
.
.
public void serVisibilityForButton(boolean shouldHide){
if(shouldHide){
yourButton.setVisibility(View.GONE);
}else{
yourButton.setVisibility(View.VISIBLE);
}
}
}
Now you can interact safely with the views of the fragment within a activity using this interface. Make sure that the fragment is alive before doing so though ;) accessing child's view are prone to WindowLeakedExceptions and illegalstateexceptions
In the activity use it as follows:
you can get the fragment reference by either finding it by its tag or by using the reference you used to create the fragment
//NOTE: it is very very dangerous to do the accessing on a fragment views from an activity
//first the alive check then the logic
if(yourFragmentReference!=null){
((AccessFragmentViews)yourFragmentReference).setVisibilityForButton(true);// or false if you want to make it visible
}
Add a method in your fragment class
public void changeButtonVisibility(boolean visibility){
if(visibility){
newDesigns.setVisibility(View.VISIBLE);
}else{
newDesigns.setVisibilty(View.GONE);
}
}
and in your activity class
add this line
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
CategoryFragment frag=(CategoryFragment) activity.getSupportFragmentManager()
.findFragmentByTag("cat_frag");
frag.changeButtonVisibility(true);
}
}

why the app crash after calling a method?

I hope you can help me I was trying to look into the other questions but I didnt found what I was trying to do or didn't get it.
this is a very simple example of what I'm trying to do. I have this main activity:
public class MainActivity extends Activity {
static EditText num1, num2; //Change EditText from TextView
static TextView num3; //Textview variable
int x, y, r;
Addition addition=new Addition();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(EditText)findViewById(R.id.editText);
num2=(EditText)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.textView);
x = 0;
y = 0;
}
public void add (View view){
setXY();
r=addition.addResult(x,y);
num3.setText(String.valueOf(r));
}
public void setXY(){
x=Integer.parseInt(num1.getText().toString());
y=Integer.parseInt(num2.getText().toString());
}
}
and I am trying to call that method from this class
public class Addition {
public int addResult(int x, int y){
return x+y;
}
}
so at the beginning the app crashed because of the null values that was receiving from the layout, but after set the try catch the app was running. The problem comes when I click the "add" button the app crash again. do you guys can tell me why? what am I doing wrong? how should I do it? and if I have an app with more "operations" ,methods, is it worth creating a class with all this operations and call them from the main one? or maybe I shouldn't try to do this?
Greetings!!!
Chiok
Logcat
07-14 14:35:24.625 5407-5407/com.chiok.x2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chiok.x2, PID: 5407
java.lang.IllegalStateException: Could not find method addition(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-14 14:35:25.893 5407-5407/com.chiok.x2 I/Process: Sending signal. PID: 5407 SIG: 9
and this is the xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.chiok.x2.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:onClick="add" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="addition" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="56dp" />
I guess it have something to do with the editable objets that are null.. but nothing that I try works.
change these code
num1=(TextView)findViewById(id.editText);
num2=(TextView)findViewById(id.editText2);
num3=(TextView)findViewById(id.editText3);
to
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
and remember to import R.java in your project.
onClick command which stored in layout need parameter View v in receiver method, so change addResult() to addResult(View v)
if I have an app with more "operations" ,methods, is it worth creating
a class with all this operations and call them from the main one?
Yes it worths that, it will make your code more object oriented. In this case it will make more sense if you change the name of class from Addition to Operations. Also Addition class does not need to be an activity. So don't extend it from MainActivity.
Just send two parameter to that method and make addResult return an int result which is addition of those two parameters.
And in your MainActivity get the return value of your addResult method and setText the edittext3.
public class MainActivity extends Activity {
TextView num1, num2,num3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
// here I am trying to call the method
Addition x = new Addition();
int param1 = Integer.parseInt(num1.getText().toString());
int param2 = Integer.parseInt(num2.getText().toString());
int result = x.addResult(param1, param2);
num3.setText(String.valueOf(result));
}
}
And your Addition Class can be like this;
public class Addition {
public int addResult(int param1, int param2){
return param1 + param2;
}
}
Summary I changed setContentView(R.layout.activity_main);
Delete extends MainActivity in your Addition class.
Also if the error still persists, I need to see your xml layout where you define your textviews and button.
Make your Textview static. Try
static TextView num1, num2,num3;
Reason
Addition x = new Addition();
In the above code, it is creating a new instance of Addition class which is extending the MainActivity and hence the TextView will be NULL for the new instance. In order to make the TextView initialization available for all instances, make the TextView static.
Use following code.
public class MainActivity extends Activity {
EditText num1, num2; //Change EditText from TextView
TextView num3; //Textview variable
Button add; //Button variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Add R.layout.activity_main
num1=(EditText)findViewById(R.id.editText); //R.id.editText
num2=(EditText)findViewById(R.id.editText2); //R.id.editText2
num3=(TextView)findViewById(R.id.textview); // initialize textview
add=(Button) findViewById(R.id.add); //initialize add button
final Addition x = new Addition();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x.addResult();
}
});
}
}
public class Addition {
public void addResult(){
try {
num3.setText(String.valueOf((Integer.parseInt(num1.getText().toString())+(Integer.parseInt(num2.getText().toString())))));
}
catch (Exception e) {}
}
}
}

error on setOnclickListener in my activity

((Button)findViewById(2131230768)).setOnClickListener(new MainMenuActivity(this));
View.OnClickListener runGameListener = new MainMenuActivity(this);
I have implemented onclicklistener even though it gives error on mainmenuactivity
my class is
public class MainMenuActivity
extends Activity implements OnClickListener
please help me..
Assume you have layout sample_activity.
Here's the code for sample_activity.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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO!!"
android:id="#+id/buttonGo"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
And MainActivity.class :
public class MainActivity extends ActionBarActivity {
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_activity);
goButton = (Button) findViewById(R.id.buttonGo);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//....Do all the stuffs here
}
});
}
First, never search for views by their generated id value. Use the identifier name instead, e.g.
findViewById(R.id.your_button)
Second, new with an Activity is not correct. Don't instantiate activities yourself.
Since your activity implements View.OnClickListener and assuming the code is in the same activity, just use
setOnClickListener(this)
That is,
findViewById(R.id.your_button).setOnClickListener(this);
(setOnClickListener() is a View method so casting to Button is not needed here.)
Firstly check your id of button from xml is write or not? I think your id is wrong its giving error..

NullPointerException on setContentView() but it exists

I have an adapter class extended to BaseAdapter that starts another activity through intent. That another activity is giving me the error:
10-10 23:58:57.171: E/AndroidRuntime(3651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.migdinny.passman/com.migdinny.passman.DataActivity}: java.lang.NullPointerException
...
10-10 23:58:57.171: E/AndroidRuntime(3651): Caused by: java.lang.NullPointerException
10-10 23:58:57.171: E/AndroidRuntime(3651): at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:77)
10-10 23:58:57.171: E/AndroidRuntime(3651): at com.migdinny.passman.DataActivity.onCreate(DataActivity.java:20)
Here's the code:
THE CODE THAT STARTS THE NEW ACTIVITY (this is inside a new listener)
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("category", category);
context.startActivity(intent);
}
THIS CODE IS THE NEW ACTIVITY THAT IS STARTED BY THE CODE ABOVE
public class DataActivity extends ActionBarActivity {
String category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // i've tried this line on all places and it doesnt fix the problem, after the setcontentview, before, etc
Intent intent = getIntent(); // this works
category = intent.getExtras().getString("category"); // this exists
setContentView(R.layout.activity_data); // THIS IS THE LINE 20 OF DATA ACTIVITY and of course that the activity_data layout exists. the eclipse does not warn me anything.
}
........
EDIT:
here's the activity_data.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.migdinny.passman.DataActivity" >
<TextView
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
the category variable that is used on onClick:
final String category = list.get(position).getCatname(); // on the beginning of getView method and i think the error is not here
Do you have any custom theming? I remember reading somewhere someone with an issue related and was related to the mind, if you have try to remove it to see if it's related (worth at try)

InstantiationException on Orientation Change when DialogFragment is on the top

I have a DialogFragment defined as inner class in my Fragment class. On Orientation Change even the following exception is poped up:
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment my.package.fragments.ImportFragment$FailedImportDialog: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:585)
at android.app.FragmentState.instantiate(Fragment.java:96)
at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1682)
at android.app.Activity.onCreate(Activity.java:861)
at my.package.activities.ImportActivity.onCreate(ImportActivity.java:8)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 12 more
Caused by: java.lang.InstantiationException: can't instantiate class my.package.fragments.ImportFragment$FailedImportDialog; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Fragment.instantiate(Fragment.java:574)
But I do have public constructor:
class FailedImportDialog extends DialogFragment {
private EditText edtPassword;
private Button button;
public FailedImportDialog() { // Here it is!
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.another_password_dialog, container, false);
edtPassword = (EditText) v.findViewById(R.id.another_password_dialog_et_password);
getDialog().setTitle(R.string.failed_to_decrypt);
Button button = (Button) v.findViewById(R.id.another_password_dialog_btn_ok);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
});
return v;
}
}
Here is xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView android:id="#+id/another_password_dialog_tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/what_password_did_you_use">
</TextView>
<EditText android:id="#+id/another_password_dialog_et_password"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="textPassword">
<requestFocus>
</requestFocus>
</EditText>
<Button android:id="#+id/another_password_dialog_btn_ok"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="OK">
</Button>
</LinearLayout>
Do you guys know why this exception happens? Thank you!
UPDATE: If I move a class to a separate file there is no such an exception, everything goes smoothly. So the question is - why this exception happens when DialogFragment is an inner class?
Calling setRetainInstance(true) will cause the FragmentManager to save your actual Fragment instance. Instead of destroying and recreating the Fragment, it will just pass the same one along to the new Activity.
try making the inner class static:
public static class FailedImportDialog extends DialogFragment
I will post more explanation about this in a while. In the meantime, try this and let me know if it works.
Define your inner class like this:
public class FailedImportDialog extends DialogFragment {
....
}
With the public notation.
Because, this is what your LogCat says:
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment
my.package.fragments.ImportFragment$FailedImportDialog: make sure class name exists
is public, and has an empty constructor that is public

Categories

Resources