Android: How do you go to another activity on click? - java

I'm trying to move onto the third activity in a sequence.
Going from the main activity to the second one works fine but when I try to go to the third activity from the second I the application crashes.
Here's my code for the second activity:
package com.example.helloandroid;
import android.app.Activity;
//other imports here
public class Game extends Activity implements OnClickListener {
private static final String TAG = "Matrix";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.matrix);
View doneButton = findViewById(R.id.done_button);
doneButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.done_button:
Intent k = new Intent(this, GameTwo.class);
startActivity(k);
//finish();
break;
}
}
}
And the code for the third activity:
package com.example.helloandroid;
import android.app.Activity;
//other imports here
public class GameTwo extends Activity {
private static final String TAG = "Matrix";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.matrixtwo);
View donetwoButton = findViewById(R.id.donetwo_button);
}
}

Try the following code in the switch:
try {
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
} catch(Exception e) {
e.printStackTrace();
}
Tell me is this helpful.....

Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
This works, but you also want to make sure that you specify this in your manifest.

Try this
Intent intent = new Intent(getApplicationContext(), GameTwo.class);
startActivity(intent);

Be sure to have the three Activities declared in the manifest. Is a common error to create the Activity and not declare it.
Call the new Activity using:
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);

It's a long shot but...
Your problem could also be caused by a NullPointerException
which is thrown if donetwo_button isn't declared in matrixtwo.xml...
(Copy-paste errors are quite common)

Related

Android studio creating new intent

I find myself trying to create a new intent to use it for switching activities in my android app using the android studio IDE.
However, I get an error saying cannot resolve constructor when I try to do so.
Here is what my code looks like.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Menu.class);
}
});
}
}
Where Menu.class is another java class empty activity
It looks like you have imported wrong menu class. Just import the one you made and it will fix this error.
How I came to this conclusion ?
Android has Menu class inbuilt , so you must have imported that class. which will throw this error.
It is a good practice to add Activity after the name of activities. for example : MenuActivity
You could call postDelayed(#NonNull Runnable r, long delayMillis) method instead. Like below:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Menu.class);
startActivity(intent);
}
},0);
if you use explicit intent, make your code like this.
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
You can also make intent in single line,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), Menu.class));
}
},1000);

How to implement startActivity() inside the OnClick() method of a separate Java class?

So i made three 3 java files.
main activity class
ButtonListener.java(Separate java class)
PurpleActivty.class(activity)
I implemented OnclickListener and OnClick method inside my ButtonListener.java file.
I want to start intent startActivity() inside my onClick(View v) of ButtonListener file. But it is throwing error on startActivity() line.
I know that i can make OnClick method under onCreate of AvtivityClass but i don't want to do this as i have made a separate java file that can handle all my button listeners.
File MainActivity.java
public class MainActivity extends AppCompatActivity {
public Button intentPurple;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentPurple=findViewById(R.id.button5);
Intent gg= new Intent(MainActivity.this, PurpleActivty.class);
ButtonListener B= new ButtonListener(gg);
intentPurple.setOnClickListener(B);
}
}
file ButtonListener.java
public class ButtonListener implements View.OnClickListener {
private Intent g;
public ButtonListener(Intent F) {
this.g=F;
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button5:
startActivity(g); // this line is error(red underline g) error msg
break; //is "startActivity() in ContextCompat cannot be
//applied to"
}}}
Any way to solve this issue?
You need to call startActivity from the context of the activity, not from your custom handler class. Refactor ButtonListener to this:
public class ButtonListener implements View.OnClickListener {
private Intent g;
private Context caller;
public ButtonListener(Intent f, Context caller) {
this.g = f;
this.caller = caller;
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button5:
caller.startActivity(g);
break;
}
}
}
Then call your listener like this:
intentPurple = findViewById(R.id.button5);
Intent gg = new Intent(MainActivity.this, PurpleActivty.class);
ButtonListener b = new ButtonListener(gg, MainActivity.this);
intentPurple.setOnClickListener(b);
I believe in
public ButtonListener(Intent F) {
this.g=F;
}
you dont have to use this, because the variable names are different.
Other than that I believe the
Intent gg= new Intent(**MainActivity.this**, PurpleActivty.class);
MainActivity.this is causing the issue as you are in a different class, you should pass MainActivity´s context as a parameter too and use
context.startActivity(g);
OR
view.getContext().startActivity(g);

How do I add data I have keyed in a EditText box into an array to list in another activity?

Below are the 3 java classes which I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array. But I am quite confused on how the logic must be for the code to send the data keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. I do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java -
https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java -
https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java -
https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
as mentioned above, the correct way would be to use the startActivityForResult method. Check this.
And how to go about it, Damn easy!
Modifying your code:
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent,123);
}
});
}
}
and in the same activity (MainActivity) listen for the result
Also would recommend you to use the parceler.org lib for sending objects
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK && requestCode==123){
// perform your list addition operation here and notify the adapter for change
// the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
// for sending parcelable pojo across activities and fragments.
list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
adapter.notifyDataSetChanged();
}
}
And in your AddActivity, when you add just do this.
public void addStudent() {
// add the 'add' button view to the oncreatemethod
// add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do not restart the activity that opened this activty
// this activity is anyways on top of the MainActivity. Just finish this activty setting the result
// Intent intent = new Intent(AddActivity.this, MainActivity.class);
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
// startActivity(intent);
// How to do that?
Student student = new Student(Fname, FphoneNumber);
Intent intent = new Intent();
intent.putExtra(YOUR_KEY, Parcels.wrap(student));
// you can also do it without the parcels lib
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
setResult(123,intent); // set the result code. it should be the same one as the one your listening on in MainAcitivty
// then just finish this activity.
finish();
// this calls the onActivtyResultMethod in MainActivity which furtther does the logic
// students.add(student);
}
});
}
That should work! Cheers!
Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here
Since you store the data in a file, the add activity should just write the data to the file. Then the main activity should always read the file to refresh the list.
I will suggest using a static class if you don't want to use a Database.
Or if you should use a file is just very simple to write into a file when you add and read from it in the next activity.
Just create a Static class like this.
public static class MyStaticClass{
private static ArrayList <Student> mStudents = new ArrayList<Student>()
public static void addStudent(Student theNewStudent){
mSudents.add(theNewStudent);
}
public static List<Student> getStudents(){
return mStudents;
}
}
or with a file:
public static class MyFileClass{
private static String pathFile = "Your path";
public static void addStudent(Student theNewStudent){
File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
file.write(/*parse your student as a string*/);
file.close();
}
public static List<Student> getStudents(){
ArrayList<Student> students = new ArrayList<>()
File file = new File(pathFile);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
//parse your line to a student object
students.add(yourNewStudent);
}
sc.close();
return students;
}
}
Just call the add student and the get students in the proper class as follows.
MyStaticClass.addStudent(student);
or
MyFileClass.addStudent(student);
Hope it helps.
In your onclick listener:
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
Student student = new Student(Fname, FphoneNumber);
MyStaticClass.addStudent(student); // or the FileClass
startActivity(intent);
}
and i cant see where do you retrieve the list. but just use the getStudents of the class.
Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);
in first Activity,
#Override
public void onAcitivityResult(....){
super();
}
in your second activity when you done,
do your stuff whatever you want in second activity. and pass it to mainActivity
Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();
IF YOU ARE USING IN FRAGMENT
if you do startActivityResult() in fragment means,
your fragment mainActivity must return super() in
public void onAcitivityResult(...){super()}
After getting the details from the student, put the respective details in a bundle and just use intent to go back to the main activity. Then use bundles to extract the data in the main activity.
You can use startActivityForResult for the same. if you haven't found the answer yet then please let me know. I will provide you the code.
Many above answers already defined this thing in a very good way.
This is about communication between Activities. You can use event bus to realize this.
https://github.com/JackZhangqj/EventBus
Then 1. Add event bus dependency to the App's build.grade
compile "de.greenrobot:eventbus:3.0.0
Register and unregister your subscribe in the MainActivity.java
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
3.Post event in the AddActivity.java
EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));
4.Implement event handling method in MainActivity
//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {
}
To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.
public class MainActivity extends AppCompatActivity {
Button addStudent;
ArrayAdapter<Student> adapter;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
ListView listView = (ListView) findViewById(R.id.listView);
listView.addAdapter(adapter);
add();
}
Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()

how I process NullPointerException on android? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I want
when I click the button.
showing Connectingreceiver.class
but NullpointerException.
I think I not well use context.
advice for me
thanks android senior developer.
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context= ConfiguredNetworkContent.this;
#Override
public void onClick(View v) {
Intent intent = new Intent(context,Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
public class Connectingreceiver extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connecting_dialog);
}
}
Check this :
private View.OnClickListener mConnectOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
Update :
Straight forward explanation is you need a Context to start a Activity. And in Onclick() there is a passing View in which Context already existed. So, I only used it to start activity.
where this context? Context context;
fix Context context = getApplicationContext;
Try this
// Add this line after Main class
Button yourButton;
In below code don't forget to edit "yourButtonIDfromXML"
// Add below code in OnCreate method after setContentView
Button yourButton = (Button) findViewById(R.id.yourButtonIDfromXML);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ConfiguredNetworkContent.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
The "context" - is null. You need to do null check s to avoid Null Pointer Crash. It is the easiest exception to resolve.
If your are doing OnClick event in
Activity:- Use these lines.
public static void startReceiver() {
Intent intent = new Intent(YourActivityName.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Fragment :-
Use these lines
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context;
#Override
public void onClick(View v) {
if(getActivity() != null) {
startActivity(getActivity());
}
}
And use same the startActivity() method
Also, rename your startActivity method. It is an inbuilt android method.
Prefer using camel cases for your class name. Connectingreceiver --> ConnectingReceiver.
I think I not well use context.
You have to use it if needed, But as per your codes there is no initialization of context.
First initialize your context either with ApplicationContext or ActivityContext like here
Context context = YourActivity.this;
then you can use startActivity(intent);. You don't need to write context.startActivity(intent);. only startActivity will be enough at all.
UPDATE :
Do not pass any context their just simply do
customstartActivity();
And inside customstartActivity() method
public static void customstartActivity (){
// Intent intent = new Intent(yourActivity.this, Connectingreceiver.class);
// Intent intent = new Intent(ContextWrapper.getBaseContext(), Connectingreceiver.class);
Intent intent = new Intent(getApplicationContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

Define generic method can open all activities

Can i define an activity in parent class of all activities that that can open new activity like this method that working:
public class ActivityBase extends Activity{
public <T extends Activity,U extends Activity> void openActivity()
{
Intent myIntent = new Intent(T.this, U.class);
T.this.startActivity(myIntent);
}
}
public class ActivityChield extends ActivityBase{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warning_unregistered_shipping);
// Set widgets reference
btnOpenActivity = (Button)findViewById(R.id.btn_wus_select_violation);
// Set widgets event listener
setListeners();
}
private void setListeners()
{
btnOpenActivity.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
openActivity<ActivityChield , OtherActivity>();
}
});
}
}
This code is not working . Please help me how can i define a method that can open all activities with one method.
I don't think this way is a perfect solution. Better is to write the calling code when you need.
By the way here is a solution for your question
public void openActivity(Class<?> calledActivity) {
Intent myIntent = new Intent(this, calledActivity);
this.startActivity(myIntent);
}
And you can call it as
openActivity(OtherActivity.class);

Categories

Resources