I am trying to access MainActivity function to my another java class. But i am not able to use these function. Please tell me what else need to be added to get it access.
My code:
Where i am trying to access my MainActivity
package com.example.musicplayer;
**import com.example.musicplayer.MainActivity;**
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class current_song extends Activity implements OnClickListener{
MainActivity ma = new MainActivity();
protected void onCreate(Bundle icicle) {
Bundle extra = getIntent().getExtras();
super.onCreate(icicle);
setContentView(R.layout.songplay_page);
if(extra != null){
String song_name = extra.getString("song_name");
TextView textchange = (TextView)findViewById(R.id.current_song_name);
textchange.setText(song_name);
textchange.setSelected(true);
}
Button btn_pause = (Button)findViewById(R.id.pause_btn);
btn_pause.setOnClickListener(this);
Button btn_next = (Button)findViewById(R.id.next_btn);
btn_next.setOnClickListener(this);
Button btn_prv = (Button)findViewById(R.id.prv_btn);
btn_prv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "In Onclick ()", Toast.LENGTH_SHORT).show();
switch(v.getId())
{
case R.id.pause_btn:
Toast.makeText(getApplicationContext(), "pause", Toast.LENGTH_SHORT).show();
ma.pause();
break;
case R.id.next_btn:
ma.next();
break;
case R.id.prv_btn:
ma.prv();
break;
}
}
}
Make sure that MainActivity has a zero argument constructor and the access specifier for pause , next and prv function is public.
In response to "i have some methods defined by me stop(), next(), pri() i am trying to access these methods when i click on each button. If you think that "creating a separate common class for sharing all methods" can you please show me 1 example bec i don't know how to access a method from 1 activity to another. "
public class myController{
private MyActivity m;
public myController(MyActivity m){
this.m = m;
}
public void stop(){
m.stop;
}
}
In other classes you initialize in the main activity and pass it the controller object so it can call the stop method
Related
I created a ListDialog extending a DialogFragment class and I have a problem with understanding of this code in the DijalogX class
((MainActivity)getActivity()).setTextField(selectedItem);
I understand that with this code above I put selected String variable to the setTextField method as an argument and after that this variable is showed in TextView on MainActivity class.
My questions:
Why I need a cast from getActivity() to the MainActivity and how I get access from DijalogX(fragment) to the method setTextField in MainActivity? Please explain a little about this process.
I also tried instead of ((MainActivity)getActivity()).setTextField(selectedItem)
use an Interface and everything works nice and I got the same resoult but I am wondering what is better solution here Interface or ((MainActivity)getActivity()).setTextField(selectedItem)?
MainActivity
package com.example.dezox.dijaloglist;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btnStartDialog;
private TextView tvSelectedOption;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
setupListener();
}
private void initWidgets() {
btnStartDialog = findViewById(R.id.btnDialog);
tvSelectedOption = findViewById(R.id.tvselectedOption);
}
private void setupListener() {
btnStartDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DijalogX dijalogX = new DijalogX();
dijalogX.show(getSupportFragmentManager(), "dx");
tvSelectedOption.setText("");
}
});
}
public void setTextField(String odabrano){
tvSelectedOption.setText(odabrano);
}
public String getTextField(){
return tvSelectedOption.getText().toString();
}
}
DijalogX
package com.example.dezox.dijaloglist;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class DijalogX extends DialogFragment {
private String[] languageList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initListResource();
}
private void initListResource() {
languageList = getResources().getStringArray(R.array.language_list);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
android.R.style.Theme_Material_Dialog_Alert)
.setTitle("Select Language: ")
.setItems(languageList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = languageList[which];
//THIS PART OF THE CODE I DONT UNDERSTAND:
((MainActivity)getActivity()).setTextField(selectedItem);
}
});
return builder.create();
}
}
You have declared a method in MainActivity called setTextField. If you called
Activity a = getActivity();
you would not be able to call your custom method (it is on your derived class, not the base Activity class).
a.setTextField(selectedIte); // WON'T WORK - NO SUCH METHOD
If instead you call
MainActivity ma = (MainActivity)getActivity();
it is now cast as your derived class and you can then call
ma.setTextField(selectedItem);
Doing it in two lines like this is the same as calling the one-liner in your code
((MainActivity)getActivity()).setTextField(selectedItem);
As far as casting vs. an interface, an interface is a bit more flexible of an approach. If you tried to use this fragment in a different activity (not MainActivity) the casting approach would fail. If you are only ever going to use the fragment in this Activity then either would work.
I m trying to create a new java file for button (sin) as this is about calculator. But it is showing Error in second override annotations. (Method does not override method from its SuperClass). There is one more Error associating with brackets in the bottom part of code. Being newbie this is the first time I'm having my hands on this part of java. I have searched many of the sites but didn't found any solution. Any help will be appreciated.
SinglesinActivity.java
package com.marsh.calculator.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
public class SinglesinActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnsin);
b.setOnClickListener(this);
}
#Override
public void onclick(View v) {
int id = v.getId();
switch (id) {
case R.id.btnsin:
break;
}
};
}
It's onClick not onclick.
Make the following changes:
#Override public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btnsin: break;
}
};
Its a typo. change onclick to onClick.
I have 2 classes BlockIdActivity.java and ScanWifi.java. I have 2 buttons in BlockIdActivity.java file and i am able to see my toast defined there. However i cant see the toast for the button i defined in ScanWifi.Java class.
Following is the code for BlockIdActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class BlockIdActivity extends ActionBarActivity {
private ImageButton mUpButton;
private ImageButton mDownButton;
private TextView mBlock_Id_Field;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block_id);
mUpButton = (ImageButton)findViewById(R.id.arrow_up);
mDownButton = (ImageButton)findViewById(R.id.arrow_down);
mBlock_Id_Field = (TextView)findViewById(R.id.BlockIdField);
mUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlock_Id_Field.getText().toString().trim().equals(""))
{
counter = 1;
mBlock_Id_Field.setText(String.valueOf(counter));
}
else {
counter = Integer.valueOf(mBlock_Id_Field.getText().toString().trim());
counter++;
mBlock_Id_Field.setText(String.valueOf(counter));
}
}
});
mDownButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int counter = Integer.valueOf(mBlock_Id_Field.getText().toString().trim());
// boolean emptyfield = mBlock_Id_Field.getText().toString().equals("");
if(counter <=1 ){
Toast.makeText(BlockIdActivity.this,
R.string.negative_blockid_toast,
Toast.LENGTH_SHORT).show();
counter = 1;
mBlock_Id_Field.setText(String.valueOf(counter));
}else {
counter--;
mBlock_Id_Field.setText(String.valueOf(counter));
}
}
});
}
}
and code for ScanWifi.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ScanWifi extends ActionBarActivity {
private Button mScanWifiButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block_id);
mScanWifiButton = (Button)findViewById(R.id.ScanWifiButton);
mScanWifiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),
R.string.ScanWifi_toast,
Toast.LENGTH_SHORT).show();
}
});
}
}
This is the strings.xml file :
<resources>
<string name="app_name">SnifferTrain</string>
<string name="BlockId">BlockId</string>
<string name="ScanWifi">ScanWifi</string>
<string name="ScanWifi_toast">ScanWifi Button Pressed</string>
<string name="negative_blockid_toast">Block Id Field Cannot Be Less Than 1 or Empty.Setting BlockID To 1</string>
<string name="action_settings">Settings</string>
</resources>
Can someone please explain why ScanWifi_toast does not show when i press ScanWifi Button. I have tried changing the context of the toast to ScanWifi.this or getApplicationContext() but it doesn't seem to work. I don't get any compilation errors. Please help
I think the problem with your string file. Do like other way:
Toast.makeText(ScanWifi.this,getResource().getString(R.string.string.ScanWifi_toast),Toast.LENGTH_SHORT).show();
Your ScanWifi activity code is not run. Hence the click listener is not registered to a button on screen and therefore the toast is not seen.
Since both your activities are using the same content view layout, you should probably move the findViewById() and setOnClickListener() to the main activity.
To launch other activities, use an Intent, e.g.
startActivity(new Intent(context, ActivityName.class));
It should be :
Toast.makeText(getBaseContext(),getResource().getString(R.string.ScanWifi_toast), Toast.LENGTH_SHORT).show();
Because R.string.ScanWifi_toast dont automatically return the String you put in your XML, it only return the id.
you should use getString(R.string.ScanWifi_toast) in place of directly using R.string.ScanWifi_toast
Use this for Toast message
Toast.makeText(getBaseContext(),
getResource().getString(R.string.ScanWifi_toast),
Toast.LENGTH_SHORT).show();
Try this
Toast.makeText(context, context.getString(R.string.ScanWifi_toast), Toast.LENGTH_LONG).show();
You can use this
Toast.makeText(getBaseContext(),"xyz",Toast.LENGTH_SHORT).show();
or
Toast.makeText(Activity.this,string,Toast.LENGTH_SHORT).show();
i have a list of object in an activity in which a button in the same activity adds an object to it on every click
i want to be capable to access that list and iterate it from any other activity
i made it public but it gave me an error !
package com.fawzyx.movie_rental_store;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MovieReg_activity extends Activity {
public List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movies.add(new movie(movName , dvdNo) );
Toast.makeText(MovieReg_activity.this, "Movie Added", Toast.LENGTH_LONG).show();
}
});
}
}
is there a way to access and iterate the list movies from any other activity ?
You can use a static way to access to this list :
public static List<movie> movies = new ArrayList<movie>();
Then from the other activity :
int size = MovieReg_activity.movies.size(); // exp: check the size
for(movie m : MovieReg_activity.movies){
// do something with m
}
if you want to make a global list, create a static variable or put it in your application class and access it via context.
Search about creating a custom application class.
Maybe use a singleton class that holds your movie list.
Then you'll be able to access it everywhere.
http://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/
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();
}