Android Setting text from a getter method in another class - android

I've looked all over the place and taken all of the tips given, but my app still force closes.
The app has two classes (Main and Next) and "Next" class has a get method. When I try to use the get method in the "Main" class my app force closes. This is the line of code that causes the problems:
timesHit_txtview.setText(next.getTimesHit());
Like I mentioned before, I don't get any errors in eclipse. The First error I get from log cat is "Uncaught handler: thread main exiting due to uncaught exception"
Any suggestions? Thanks in advance
EDIT:
package com.whatever.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Next next = new Next();
TextView timesHit_txtview = (TextView) findViewById(R.id.textView2);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timesHit_txtview.setText(5);
Button next_btn = (Button) findViewById(R.id.button1);
next_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextscreen_intent = new Intent(view.getContext(), Next.class);
startActivityForResult(nextscreen_intent, 0);
}
});
}
}

You're trying to initialize a widget before the onCreate() call has been completed.
Initialize your TextView in the onCreate() method before you call setText on it, like so:
public class MainActivity extends Activity {
Next next;
TextView timesHit_txtview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next = new Next(); // Initialize Next
timesHit_txtview = (TextView) findViewById(R.id.textView2); // Initialize Widget
timesHit_txtview.setText(5);
Button next_btn = (Button) findViewById(R.id.button1);
next_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextscreen_intent = new Intent(view.getContext(), Next.class);
startActivityForResult(nextscreen_intent, 0);
}
});
}
In your current code, timesHit_txtview is null when you try to set a text for it, which makes you Activity crash.

Related

A simple app with a textview and two buttons that trigger toasts not working

It's just a simple text with two buttons that creates toasts and change the text. I'm very new to this AS so I really don't know how to even attempt to fix this..
Any help is very appreciated...
MainActivity.java:
package com.example.david.davidisawesome;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
final TextView firstText = (TextView) findViewById(R.id.firstText);
Button firstButton = (Button) findViewById(R.id.firstBtn);
Button secondButton = (Button) findViewById(R.id.secondBtn);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: First Button Clicked.");
toastMessage("You Clicked the first button");
firstText.setText("Nice Job.");
}
});
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Second Button Clicked.");
toastMessage("You Clicked the second button");
firstText.setText("Good Effort.");
}
});
}
private void toastMessage(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
In picture:
activity_main.xml:
Error:
It is not finding your xml elements. The error shows that you have a null exception on setting the onclick interface to the button. So start by confirming that you are inflating the proper xml and finding the proper id.
More specifically your secondBtn is not found.

Android - changing textview from other activity

I'm quite new to programming.
I'm trying to make a simple app with two activities, where the second activity can change the text of the first. I know it can be done using intents, but I was wondering if there is a more direct way of doing it, for example using the second activity to call a function from the first activity?
Here's the code I have so far:
The MainActivity, which contains a TextView and a button to open the second activity:
public class MainActivity extends Activity {
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.et2);
button = (Button) findViewById(R.id.b1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, ChangeText.class);
startActivity(intent);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public void changetext(String message) {
textview.setText(message);
}
}
And the second activity, ChangeText, which contains an EditText and a button which should change the text of the TextView in MainActivity and then finish itself:
public class ChangeText extends Activity{
EditText edittext;
Button button;
private MainActivity mainclass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_text);
edittext = (EditText)findViewById(R.id.et2);
button = (Button)findViewById(R.id.b2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = edittext.getText().toString();
mainclass.changetext(message);
finish();
}
});
}
}
As you can see I tried to make the app work by making a public function in MainActivity which receives a string and sets the TextView with it, and then I call this function from the ChangeText activity.
The problem: it keeps crashing! Can anyone tell me how I can make this work?
Seems like I answered almost exactly the same question a week or so ago, so this is probably a duplicate, but I can't seem to find the original question.
The short answer is no - you can't call a method in an Activity from another Activity. The issue is that for normal programming purposes, only one Activity exists at a time*.
If you do something to circumvent this, then you're risking causing some major issues, including high memory usage, null pointer exceptions, etc.
The correct way to do this is indeed through the Intent system.
* Activities may or may not actually get destroyed when they become inactive, depending on things like how you use the back stack.
However, you should always program is if they do get destroyed when they become inactive - read, understand, and respect the Activity lifecycle.
For something as simple as your app, the "most direct" approach is to use the intent and startActivityForResult and them implement an onActivityResult in your main activity.
The problem you'll run into, even if you correctly pass you Activity references around is they are not guaranteed to be running at the same time.
Other ways aside from Intents, is to use a class(s) not involved with the Activity. Either a background service or a static variable in a class that extends Application. I rarely use Application classes anymore in favor of services and binding Activities them.
If I use an EventBus in projects, they can send Sticky events, which will hold the data until cleared.
Android uses a messaging mechanism to communicate between its components. This messaging mechnism is essential to Android, so you should use it. And as you already said, the messaging is implemented by Intents. ;-)
If you want something more complex, use an EventBus or implement a your own subscribe/publish mechanism that does what you want.
Use static variable
Example
In your MainActivity define
public static String msg = null;
then in your ChangeText activity assign changed text to it like
MainActivity.msg = edittext.getText().toString();
now in your main activity override the onResume() methode
if(msg != null){
textview.setText(msg);
msg = null;
}
You must LocalBroadCast Manager to do so
Here is the MainActivity which has the TextView which has to updated by another Activity
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.txt1);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String s1= intent.getStringExtra("myString");
getIt(s1);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
public void getIt(String s)
{
System.out.println(s);
txt.setText(s);
}
public void go(View view)
{
Intent intent = new Intent(this,WriteText.class);
startActivity(intent);
}
}
And This is the Activity which contains the EditText which updates the TextView in the previous activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class WriteText extends Activity {
EditText ed1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_text);
ed1 = (EditText)findViewById(R.id.textView);
}
public void come(View view){
Intent intent = new Intent("custom-event-name");
intent.putExtra("myString", ed1.getText().toString());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
This Worked for me , Hope it works for you too

Activity not moving to next activity when button click in android?

I am trying to move from one activity to another activity by clicking to the ImageButton. But when I click to button, it doesn't move to the activity which I specify in the code, and even it does not throw an error. I'm not getting where is problem
Here is my code which calls next activity :
package com.birthdayreminder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class Reminder extends Activity {
ImageButton view, add, edit;
TextView tvadd, tvedit, tvview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
}
public void innicialize() {
// assigning buttons
view = (ImageButton) findViewById(R.id.bView);
add = (ImageButton) findViewById(R.id.bAdd);
edit = (ImageButton) findViewById(R.id.bEdit);
// assign textview
tvadd = (TextView) findViewById(R.id.tvAdd);
tvedit = (TextView) findViewById(R.id.tvEdit);
tvview = (TextView) findViewById(R.id.tvView);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Reminder.this, Addreminder.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bEditBtn click here
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bViewBtn click here
}
});
}
}
I have also declared the class name in the manifest.xml but it does not working
Logcat Log file : 5 lines of last logcat file after clicking the button :
05-15 18:19:25.495: W/AudioFlinger(33): write blocked for 69 msecs, 1245 delayed
writes, thread 0xc658
05-15 18:19:28.964: I/ActivityManager(60): Starting: Intent {
act=com.birthdayreminder.REMINDER cmp=com.birthdayreminder/.Reminder } from pid 548
05-15 18:19:29.409: I/ActivityManager(60): Displayed
com.birthdayreminder/.Reminder: +426ms
try using getApplicationContext() in place of Remainder.this
check if you have a click listener on you imagebutton, you have declared what to do on click, but if you don't have any listener on the imagebutton, it won't work anyway.
You can try something like this :
yourImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Reminder.this, Addreminder.class);
startActivity(intent);
}
});
After doing this, you must have declared in your XML file the activity
<activity android:name="packageName.className" />
Finally, check if the new class is working well too but it must be ok!
==================================================================================
You mustn't declare a function or procedure in a function (like you did in onCreate), you can simply do what you do in initialize in your onCreate function like this :
package com.birthdayreminder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class Reminder extends Activity {
private ImageButton view;
private ImageButton add;
private ImageButton edit;
private TextView tvadd;
private TextView tvedit;
private TextView tvview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
// Instantiating Buttons
view = (ImageButton) findViewById(R.id.bView);
add = (ImageButton) findViewById(R.id.bAdd);
edit = (ImageButton) findViewById(R.id.bEdit);
// Instantiating Views
tvadd = (TextView) findViewById(R.id.tvAdd);
tvedit = (TextView) findViewById(R.id.tvEdit);
tvview = (TextView) findViewById(R.id.tvView);
// Adding a clickListener on add button
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Reminder.this, Addreminder.class);
startActivity(i);
}
});
// Adding a clickListener on edit button
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bEditBtn click here
}
});
// Adding a clickListener on view button
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bViewBtn click here
}
});
}
}
If you still have a problem, check your XML files, and look if you have well declared your buttons.
Problem Fixed: Never define a function in a function, because everytime you call the first function you'll define again the second function.
What you did which is wrong :
onCreate { //WRONG VERSION
bla bla bla bla
initialisation {
bla bla bla
}
}
What you have to do :
onCreate { //GOOD VERSION
initialisation();
bla bla bla
}
initialisation {
bla bla bla
}
you can call a function in a function, but you can't define a function in a function.
Moreover, you never call your initialisation function, you must call it now in your onCreate function or nothing will happen.
have you set onClickListener on add button.
btnAdd.setOnClickListener(this);
also check the
is your v.getId() and case R.id.bAdd: same?
debug and check that your case R.id.bAdd: is getting executed..
Seperately initialize the buttons in the first activity as
Button bAddbutton= (Button) findViewById(R.id.bAdd);
Button bEditBtn= (Button) findViewById(R.id.bEdit);
Button bViewBtn= (Button) findViewById(R.id.bView);
Then add seperate onClick listeners for each button as given below,
bAddbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Reminder.this, Addreminder.class);
startActivity(i);
}
});
bEditBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bEditBtn click here
}
});
bViewBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// enter the code for bViewBtn click here
}
});
initialize the button and add listener first in oncreate()
Button btnAdd = (Button) findViewById(R.id.bAdd);
btnAdd.setOnClickListener(this);

ListView: Null pointer exception

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}

Displaying Another Screen Onclick in Android

package com.example.example;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
this.setContentView(R.layout.activity_main);
this.btn = (Button)this.findViewById(R.id.button);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, profile.class);
startActivity(intent);
}
});
}
}
I don't get any errors however my program also dont run as I want. I am new in android and I want to change the screen after the button is clicked for that I am using two classes so in one class my program should invoke another one onclick. How can I do this ? My code is as above.
First remove this.setContentView(R.layout.activity_main); because you declared it twice . Then declare
btn = (Button)this.findViewById(R.id.button);
after
setContentView(R.layout.activity_main);
Declare your profile activity in manifest file.Check my code below.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)this.findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, profile.class);
startActivity(intent);
}
});
1) your oncreate method should look like below one.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)this.findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, profile.class);
startActivity(intent);
}
});
2) Add profile Activity into Manifest.
3) add logs in onClick method so you should know if it is getting called on not.
Happy coding!!

Categories

Resources