This problem seems to be common and I have looked at the other similar questions but none have helped my situation.
I have an activity with a fragment that has a button. When the button is clicked I get the following error and I don't know why:
java.lang.IllegalStateException: Could not find a method onSaveIdeaButtonClick(View) in the activity class com.zarwanhashem.ideatrackr.EditIdeaPageActivity for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'saveIdeaButton'
But when I do control + click on the onClick attribute in the XML in IntelliJ it takes me to the onClick method in the activity correctly.
This is the button xml:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save_edit_bttn"
android:id="#+id/saveIdeaButton"
android:onClick="onSaveIdeaButtonClick"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
This is the EditIdeaPageActivity class:
public class EditIdeaPageActivity extends AppCompatActivity {
private static final String IDEA_TITLE_KEY = "title";
private static final String IDEA_DETAILS_KEY = "details";
private Context myContext;
private static SharedPreferences sharedPref;
private int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_idea_page);
myContext = getApplicationContext();
Intent intent = getIntent();
EditText ideaTitle = (EditText)findViewById(R.id.ideaTitle);
EditText ideaDetails = (EditText)findViewById(R.id.ideaDetails);
sharedPref = myContext.getSharedPreferences("sharedPref", 0);
if (intent != null) {
setTitle(intent.getStringExtra("title"));
ideaTitle.setText(intent.getStringExtra(IDEA_TITLE_KEY));
ideaDetails.setText(intent.getStringExtra(IDEA_DETAILS_KEY));
} else {
setTitle("Error - no idea provided to edit");
ideaTitle.setText("Error");
ideaDetails.setText("Error");
id = intent.getIntExtra("ID", -1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSaveIdeaButtonClicked(View v) {
SharedPreferences.Editor editor = sharedPref.edit();
EditText ideaTitle = (EditText)findViewById(R.id.ideaTitle);
EditText ideaDetails = (EditText)findViewById(R.id.ideaDetails);
editor.putString(IDEA_TITLE_KEY, ideaTitle.getText().toString());
editor.putString(IDEA_DETAILS_KEY, ideaDetails.getText().toString());
editor.commit();
Intent intent = new Intent(v.getContext(), MainActivity.class);
intent.putExtra(IDEA_TITLE_KEY, ideaTitle.getText().toString());
intent.putExtra(IDEA_DETAILS_KEY, ideaDetails.getText().toString());
intent.putExtra("Edit", true);
intent.putExtra("ID", id);
startActivity(intent);
}
}
Why is it saying that the method cannot be found? Please let me know if more details are needed.
Your xml: android:onClick="onSaveIdeaButtonClick" and your method is public void onSaveIdeaButtonClicked(View v).
Change your method for:
public void onSaveIdeaButtonClick(View v)
Related
In a ListView populated by an ArrayList, how can I limit the number of characters per list item or limit each list item to only one line of text? It's a notes app. all my code is below.
ListView:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:singleLine="true"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> note;
ListView listView;
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
static Set<String> set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
setTitle("Notely");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notes.add("");
SharedPreferences sharedPreferences = getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
arrayAdapter.notifyDataSetChanged();
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", notes.size() - 1);
startActivity(i);
}
});
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
set = sharedPreferences.getStringSet("notes", null);
notes.clear();
if (set != null) {
notes.addAll(set);
} else {
notes.add("Example note");
set = new HashSet<String>();
set.addAll(notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", position);
startActivity(i);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notes.remove(position);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
EditNote.java
public class EditNote extends AppCompatActivity implements TextWatcher{
int noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Write a Note");
EditText editText = (EditText) findViewById(R.id.editText);
Intent i = getIntent();
noteId = i.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
}
editText.addTextChangedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.notes.set(noteId, String.valueOf(s));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (MainActivity.set == null) {
MainActivity.set = new HashSet<String>();
} else {
MainActivity.set.clear();
}
MainActivity.set.addAll(MainActivity.notes);
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", MainActivity.set).apply();
}
#Override
public void afterTextChanged(Editable s) {
}
}
You are currently using a built-in layout (android.R.layout.simple_list_item_1) for each item in your List View. It sounds like you want to customize this. So you need to create your own layout with a <TextView> with appropriate attributes, including
android:maxLines="1"
android:ellipsize="end"
Setting the maxLines to one and ellipsize to end is not going to work when you apply those settings to the ListView itself. Instead, you have a layout you are inflating for your ListView items. I am assuming that it contains a TextView since you want to have a single line with ellipsis instead of a TextView whose content grows vertically. Add these lines to the TextView within your List item layout. Again, this layout is the one you are inflating for each ListView item.
android:maxLines="1"
android:ellipsize="end"
You will then use this layout to create your adapter. Also note that you call setAdapter() twice, which is unnecessary.
I have 3 tabs in my dashboard namely,
Invitation
Event
Groupchat
I am added all those tabs programmatically,In my layout code id:tabContent using for add all my tabs. My Userdashboard.xml code is below,
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-4dp"
android:layout_weight="0" />
</LinearLayout>
In below code all tabs are grouped as "tabHost". Now i am need to set unique id for all the three tabs, but i dont know how to set unique id for that help me please thanks in advance.
public class UserDashBoardActivity extends ActionBarActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Event";
private static final String TAB_3_TAG = "GroupChat";
private FragmentTabHost tabHost;
private Context context;
private SharedPreferences sharedpreferences;
private Gson gson = new Gson();
private Menu menu;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_user_dash_board, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
// Get TabHost Reference
tabHost= (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
**Invitation,Event,Groupchat tabs** are added here
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator("Invitation"), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator("Event"), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator("GroupChat"), GroupChatFragment.class, null);
//invitation tab highlighted by default
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.Orange));
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.scandal));
tabHost.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.scandal));
//onTabChangedListener added for move one tab to others
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
setTabColor(tabHost);
}
});
}
if(tabHost.getCurrentTab()==0)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange));//1st tab selected
else if(tabHost.getCurrentTab()==1)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //2nd tab selected
else if(tabHost.getCurrentTab()==2)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //3rd tab selected
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.account_settings) {
Intent userSettingIntent = new Intent(getApplicationContext(),ActivityUserSettings.class);
userSettingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(userSettingIntent);
return true;
}
if (id == R.id.profile) {
Intent profileIntent = new Intent(getApplicationContext(),ImageUploadActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profileIntent);
return true;
}
if(id == R.id.create_occasion){
Intent occasionAct = new Intent(getApplicationContext(), OccasionActivity.class);
// Clears History of Activity
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
return super.onOptionsItemSelected(item);
}
}
The call to tabHost.newTabSpec() takes a String as tag. In your case these are TAB_1_TAG, TAB_2_TAG, TAB_3_TAG, so these are your unique IDs for each tab respectively.
You can identify the selected tab in onTabChanged(String arg0) here arg0 is the name of the selected tag.
Furthermore you can use tabHost.getCurrentTabTag() to identify tabs by tag instead of tabHost.getCurrentTab() which is by tab position.
So, When I try to launch this application it crashes. However, it only crashes when I try to use the setOnClickListener. If I comment out that small section it runs just fine.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button button = (Button)findViewById(R.id.button);
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//textView.setText("Boop!");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
OK Working code! I had to move super.onCreate up, and declair the textview inside the findviewbyID section. However, now it works as I intended. Thank you guys for the help! I just wanted to make something very basic for a date. xD you guys are a life saver.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Boop!");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
WORKING
The error is coming because you are calling the super.onCreate(savedInstanceState);
after the setContentView and then using the variables.
Reason that the error is not coming until you don't write onClicklister:
The variables textView and button are already null or in inconsistent state, but when you are writing the click listener, the variables are used and you are facing error.
You declared textView as final:
A variable can be declared final. A final variable may only be assigned to once.
final TextView textView = (TextView) findViewById(R.id.textView);
so you cannot modify it.
You must get the view inside onclick method:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Boop!");
}
});
I have 3 buttons on my Layout. And I've tried to set one click listener on them but my app crashes when it starts.
No warnings in Android Studio.
At first I create new Click listener - buttonsClickListener. Then with switch I separate exe codes for every button. And in onCreate method I set listeners to buttons.
public class MainActivity extends ActionBarActivity {
private RelativeLayout mRelativeLayout;
private TextView mInfoTextView;
Button buttonSetBackgroundRed =(Button) findViewById(R.id.buttonSetBackgroundRed);
Button buttonSetBackgroundYellow =(Button) findViewById(R.id.buttonSetBackgroundYellow);
Button buttonSetBackgroundGreen =(Button) findViewById(R.id.buttonSetBackgroundGreen);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
mInfoTextView = (TextView) findViewById(R.id.infoTextView);
buttonSetBackgroundRed.setOnClickListener(buttonsClickListener);
buttonSetBackgroundYellow.setOnClickListener(buttonsClickListener);
buttonSetBackgroundGreen.setOnClickListener(buttonsClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
View.OnClickListener buttonsClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonSetBackgroundRed:
mInfoTextView.setText(R.string.set_background_red);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.redColor));
break;
case R.id.buttonSetBackgroundYellow:
mInfoTextView.setText(R.string.set_background_yellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.yellowColor));
break;
case R.id.buttonSetBackgroundGreen:
mInfoTextView.setText(R.string.set_background_green);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.greenColor));
break;
}
}
};
}
You can't use findViewById() outside of the onCreate() method because the views aren't even created before onCreate() is called. So, there's no view to find. Change your code to the following
public class MainActivity extends ActionBarActivity {
private RelativeLayout mRelativeLayout;
private TextView mInfoTextView;
Button buttonSetBackgroundRed;
Button buttonSetBackgroundYellow;
Button buttonSetBackgroundGreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSetBackgroundRed =(Button) findViewById(R.id.buttonSetBackgroundRed);
buttonSetBackgroundYellow =(Button) findViewById(R.id.buttonSetBackgroundYellow);
buttonSetBackgroundGreen =(Button) findViewById(R.id.buttonSetBackgroundGreen);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
mInfoTextView = (TextView) findViewById(R.id.infoTextView);
buttonSetBackgroundRed.setOnClickListener(buttonsClickListener);
buttonSetBackgroundYellow.setOnClickListener(buttonsClickListener);
buttonSetBackgroundGreen.setOnClickListener(buttonsClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
View.OnClickListener buttonsClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonSetBackgroundRed:
mInfoTextView.setText(R.string.set_background_red);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.redColor));
break;
case R.id.buttonSetBackgroundYellow:
mInfoTextView.setText(R.string.set_background_yellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.yellowColor));
break;
case R.id.buttonSetBackgroundGreen:
mInfoTextView.setText(R.string.set_background_green);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.greenColor));
break;
}
}
};
}
try to use onClick property of button in xml file and make one call of it in your code like this,
<?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/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btn"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btn"
android:text="Button" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btn"
android:text="Button" />
</LinearLayout>
And in you Activity class make this method,
public void btn(View v){
//Your code on clicked
}
by this your code will also reduced.....
public class MainActivity extends ActionBarActivity {
private RelativeLayout mRelativeLayout;
private TextView mInfoTextView;
Button buttonSetBackgroundRed =(Button)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.buttonSetBackgroundRed);
Button buttonSetBackgroundYellow =(Button) findViewById(R.id.buttonSetBackgroundYellow);
Button buttonSetBackgroundGreen =(Button) findViewById(R.id.buttonSetBackgroundGreen);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
mInfoTextView = (TextView) findViewById(R.id.infoTextView);
buttonSetBackgroundRed.setOnClickListener(buttonsClickListener);
buttonSetBackgroundYellow.setOnClickListener(buttonsClickListener);
buttonSetBackgroundGreen.setOnClickListener(buttonsClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
View.OnClickListener buttonsClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonSetBackgroundRed:
mInfoTextView.setText(R.string.set_background_red);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.redColor));
break;
case R.id.buttonSetBackgroundYellow:
mInfoTextView.setText(R.string.set_background_yellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.yellowColor));
break;
case R.id.buttonSetBackgroundGreen:
mInfoTextView.setText(R.string.set_background_green);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.greenColor));
break;
}
}
};
}
My group is trying to make a contactlist which contacts can be addded too, However they are getting the following error : Non-static method populatelist() cannot be referenced through a static context. However we don't know if this then will actually work. Any help is appreciated
public class Profile extends Activity {
ImageView contactImageImgView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
Button editProfileButton = (Button) findViewById(R.id.BeditProfile);
Button addContactButton = (Button) findViewById(R.id.AdContactButton);
//Text ChangeProfilePictureText = (Text) findViewById(R.id.ChangeProfilePicture);
String Name = getIntent().getStringExtra("Name");
String eMail = getIntent().getStringExtra("Mail");
String Mobile = getIntent().getStringExtra("Mobile");
String Adress = getIntent().getStringExtra("Adress");
String Bio = getIntent().getStringExtra("Bio");
contactImageImgView = (ImageView) findViewById(R.id.imgViewContactImage);
TextView tv_Name = (TextView) findViewById(R.id.Name);
TextView tv_Mail = (TextView) findViewById(R.id.Email);
TextView tv_Mobile = (TextView) findViewById(R.id.Mobile);
TextView tv_Adress = (TextView) findViewById(R.id.Adress);
TextView tv_Bio = (TextView) findViewById(R.id.Bio);
tv_Name.setText(Name);
tv_Mail.setText(eMail);
tv_Mobile.setText(Mobile);
tv_Adress.setText(Adress);
tv_Bio.setText(Bio);
if(Cube.fromUnit){
editProfileButton.setVisibility(View.GONE);
//ChangeProfilePictureText.replaceWholeText("");
tv_Name.setText(Cube.Name);
tv_Mail.setText(Cube.eMail);
tv_Mobile.setText(Cube.Mobile);
tv_Adress.setText(Cube.Adress);
tv_Bio.setText(Cube.Bio);
}
contactImageImgView.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){ // error # View v, cannot resolve symbol v , expected ;
Intent intent = new Intent();
intent.setType("image*/");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(intent.createChooser(intent, "Select Profile Image"), 1);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_home) {
Intent i = new Intent(this, HomeScreen.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public void onButtonClick(View v) {
if (v.getId() == R.id.BeditProfile) {
Intent i = new Intent(Profile.this, editProfile.class);
startActivity(i);
}
if (v.getId() == R.id.AdContactButton) {
MainActivity.addContact(Cube.Name, Cube.Adress, "", Cube.Mobile, Cube.eMail);
MainActivity.populateList();
Toast pass = Toast.makeText(this, Cube.Name + " " + "Has been added to your contacts", Toast.LENGTH_LONG);
pass.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
pass.show();
}
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK){
if(reqCode == 1)
contactImageImgView.setImageURI(data.getData());
}
}
}
We got a new crash regarding our button "add contact" . Which says that populateList cannot be executed
You cannot refer to MainActivity.populateList(); if populateList declaration is not static.Check JLS (ยง8.5).
You must create an instance of MainActivity
MainActivity ma = new MainActivity(); // or another constructor
ma.populateList(); // valid call of method
Or, if you don't need the instance of MainActivity declare populateList() as follows:
public static void populateList()