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.
Related
I did something that destroyed my project. It worked on my latest commit 22 hours ago.
I'm using recylerview to get data from logged in user. I can't even see that the recylerview is on my page anymore. How can I revert back to my latest commit in android studio I did one 22 hours ago. I've tried everything I don't understand things. I did not even touch that activity today but 2 hours ago it stopped working.
only thing i did was to refactor the view called custom_layout used for editing notes but i reverted that afterwards maybe something got saved somewhere and causing the error
here is a picture of my view:
enter code here (MODEL)
package com.example.examapplikation.Models;
public class NotesList {
private String title;
private String text;
public NotesList(){
}
public NotesList(String title, String text){
this.title=title;
this.text= text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
VIEWHOLDER! enter code here
package com.example.examapplikation.ViewHolder;
public class NoteViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public TextView text_title, text_content;
public NoteViewHolder(#NonNull View itemView){
super (itemView);
text_title = itemView.findViewById(R.id.text_title);
text_content = itemView.findViewById(R.id.text_content);
itemView.setOnCreateContextMenuListener(this); // context to this view
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { // on clik update delete on every object
// menu.setHeaderTitle("Select desired option");
menu.add(0,0,getAdapterPosition(),"Edit Note");
menu.add(0,0,getAdapterPosition(),"Delete Note");
}
}
MAINACTIVITY
enter code here
package com.example.examapplikation;
public class HomeActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FloatingActionButton addNotePageButton;
private FirebaseAuth firebaseAuth;
FirebaseDatabase database;
DatabaseReference notesDb;
FirebaseRecyclerOptions<NotesList> options;
FirebaseRecyclerAdapter<NotesList, NoteViewHolder> adapter; // adapter
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//iniate
viewSetUp();
// refrense
notesDb = database.getReference("NoteList").child(firebaseAuth.getCurrentUser().getUid());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager( new LinearLayoutManager(this) );
showEachRow(); // call function
// buton to add note
addNotePageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, NoteInputActivity.class);
startActivity(intent);
}
});
}
//Region -used for edit and delete this section start reads whats in the post and open ups a window on the same window based on the Viewholder and a xml file called custom_layout
// recycler view in this section and only the verifed logged in user can See his own data!
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) { // viewholder
if (item.getTitle().equals("Edit Note")){
showUpdateDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
} else if (item.getTitle().equals("Delete Note")){
deleteNote(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteNote(String adapter) { // delete
notesDb.child(adapter).removeValue();
}
private void showUpdateDialog(final String key, NotesList item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("[ Note Edit Mode]");
builder.setMessage("Please update the desired fields");
View update_layout = LayoutInflater.from(this).inflate(R.layout.custom_layout,null); // view model layou
final EditText changed_title = update_layout.findViewById(R.id.edit_update_title);
final EditText changed_content = update_layout.findViewById(R.id.edit_update_text);
changed_title.setText(item.getTitle()); // get value to new
changed_content.setText(item.getText());
builder.setView(update_layout);
builder.setPositiveButton("Save changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = changed_title.getText().toString();
String content = changed_content.getText().toString();
NotesList notesList = new NotesList(title,content);
notesDb.child(key).setValue(notesList);
Toast.makeText(HomeActivity.this,"Note Updated", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
//# EndRegion
// Region to read data from dataBase using Viewholder and model Notes and a xml file called note_each_row + the home xml file.
private void showEachRow(){ // recycler view
options = new FirebaseRecyclerOptions.Builder<NotesList>()
.setQuery(notesDb,NotesList.class)
.build();
adapter = new FirebaseRecyclerAdapter<NotesList, NoteViewHolder>(options) { // noteViewModel to model to get
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder holder, int position, #NonNull NotesList model) {
holder.text_title.setText(model.getTitle());
holder.text_content.setText(model.getText());
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.notes_each_row,viewGroup,false); // inflate the rows
return new NoteViewHolder(itemView);
}
};
recyclerView.setAdapter(adapter);
}
//# end Region
//#start region initate to xml
private void viewSetUp(){
recyclerView = findViewById(R.id.recyclerView);
addNotePageButton = findViewById(R.id.fab_button_addPage);
firebaseAuth = FirebaseAuth.getInstance(); // get inSTACE
database = FirebaseDatabase.getInstance();
}
// end region
//# Menu
private void Logout(){ // sign out method called in switchcase
firebaseAuth.signOut();
finish();
startActivity(new Intent(HomeActivity.this,MainActivity.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) { //create menu on toolbar
getMenuInflater().inflate(R.menu.menu,menu); //inflated inside
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { // handle on click events on items on menu
switch(item.getItemId()){
case R.id.logoutMenu:{
Logout();
finish();
break;
}
case R.id.ProfileMenu:{
startActivity(new Intent(HomeActivity.this,ProfileActivity.class));
finish();
break;
}
case R.id.HomeMenu:{
startActivity(new Intent(HomeActivity.this,HomeActivity.class));
finish();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
// Endregion
XML for each row in the recyclerVIEW
enter code here
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<ImageView
android:id="#+id/random"
android:layout_width="45dp"
android:layout_height="37dp"
android:src="#drawable/note" />
<TextView
android:id="#+id/text_title"
android:background="#color/LightPink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
style="#style/TextAppearance.AppCompat.Headline"/>
<View
android:layout_marginTop="5dp"
android:id="#+id/fillView"
android:layout_width="fill_parent"
android:layout_height="3dp"
android:background="#c0c0c0"/>
<TextView
android:id="#+id/text_content"
android:text="content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Even if I don't get data anymore I should be able to see the cardview on my page..?
Don't worry these maybe help you:
This maybe related to low memory and indexing .
Restart your computer
start your ide(android studio)
Build-->Clean
Build-->Rebuild project
File-->Invalidate caches/Restart-->Invalidate and restart
After restarting of android studio(in previous step): File-->Sync with file system
File-->Sync project with gradle files
Close your project
Restart android studio
10.Open your project after some minutes.
I am trying to retrieve data from server and display it in listview. But when I compile this it is not working and the list is even not showing in the activity.
Mylist.xml
<?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:layout_marginTop="#dimen/fab_margin"
android:orientation="vertical" >
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/edItem"
android:layout_width="180dp"
android:layout_marginTop="10dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:orientation="horizontal">
<TextView
android:id="#+id/edUnit"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edPrice"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edDisc"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</AbsoluteLayout>
</LinearLayout>
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.user.merchant.MainActivity"
tools:showIn="#layout/app_bar_main">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:dividerHeight="10dp">
</ListView>
<SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</SearchView>
</RelativeLayout>
AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
// private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
CustomFilter filter;
private LayoutInflater inflater;
private List<InventoryModel> InventoryModelItems;
private List<InventoryModel> filterList;
public CustomListAdapter(Activity activity, List<InventoryModel> InventoryModelItems) {
this.activity = activity;
this.InventoryModelItems = InventoryModelItems;
this.filterList=InventoryModelItems;
}
#Override
public int getCount() {
return InventoryModelItems.size();
}
#Override
public Object getItem(int location) {
return InventoryModelItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.mylist, null);
TextView ItemName = (TextView) convertView.findViewById(R.id.edItem);
TextView Unit = (TextView) convertView.findViewById(R.id.edUnit);
TextView Price = (TextView) convertView.findViewById(R.id.edPrice);
TextView Discount = (TextView) convertView.findViewById(R.id.edDisc);
// getting InventoryModel data for the row
InventoryModel m = InventoryModelItems.get(position);
// thumbnail image
// title
ItemName.setText(m.getItemName());
// rating
Unit.setText("Unit: " + (m.getUnit()));
// release year
Price.setText("Rs: " + String.valueOf(m.getPrice()));
Discount.setText("Discount: " + String.valueOf(m.getUnit()));
return convertView;
}
#Override
public Filter getFilter() {
if(filter==null)
{
filter=new CustomFilter();
}
return filter;
}
class CustomFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint != null&&constraint.length()>0)
{
constraint=constraint.toString().toUpperCase();
ArrayList<InventoryModel> filters=new ArrayList<InventoryModel>();
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getItemName().toUpperCase().contains(constraint))
{
InventoryModel p= new InventoryModel(filterList.get(i).getItemName(),filterList.get(i).getUnit(),filterList.get(i).getPrice(),filterList.get(i).getDiscount());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}
else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
InventoryModelItems=(List<InventoryModel>) results.values;
notifyDataSetChanged();
}
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "url";
private ProgressDialog pDialog;
private List<InventoryModel> InventoryModelList = new ArrayList<InventoryModel>();
private ListView listView;
private CustomListAdapter adapter;
public TextView test;
SearchView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, InventoryModelList);
listView.setAdapter(adapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setLogo(R.drawable.ic_menu_slideshow);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_slideshow));
// test=(TextView)findViewById(R.id.listtest);
setSupportActionBar(toolbar);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
assert getSupportActionBar() != null;
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest InventoryModelReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// test.setText(response);
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
InventoryModel InventoryModel = new InventoryModel();
InventoryModel.setItemName(obj.getString("Item_Name"));
InventoryModel.setUnit(obj.getString("Unit"));
InventoryModel.setPrice(((Number) obj.get("Price"))
.floatValue());
InventoryModel.setDiscount(((Number) obj.get("Discount")).floatValue());
// adding InventoryModel to InventoryModels array
InventoryModelList.add(InventoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(InventoryModelReq);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intenthome = new Intent(MainActivity.this, MainActivity.class);
startActivity(intenthome);
}
});*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentfloat = new Intent(MainActivity.this, ItemAdd.class);
startActivity(intentfloat);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//toggle.setHomeAsUpIndicator(R.drawable.ic_menu_slideshow);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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.account) {
Intent intentaccount = new Intent(MainActivity.this, account.class);
startActivity(intentaccount);
}
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.action_notify) {
Intent intentNotify = new Intent(MainActivity.this, Notification.class);
startActivity(intentNotify);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_processing) {
// Handle the camera action
Intent intentProcessing = new Intent(MainActivity.this, ProcessingItem.class);
startActivity(intentProcessing);
} else if (id == R.id.nav_processed) {
Intent intentProcessed = new Intent(MainActivity.this, ProcessedItem.class);
startActivity(intentProcessed);
} else if (id == R.id.nav_Aborted) {
Intent intentAborted = new Intent(MainActivity.this, AbortedIem.class);
startActivity(intentAborted);
} else if (id == R.id.nav_delivery) {
Intent intentDelivered = new Intent(MainActivity.this, DeliveredItem.class);
startActivity(intentDelivered);
}
else if (id == R.id.logout)
{
// private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivityMerchant.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
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)
EDIT Added MyActivity.java (i.e., main activity) at bottom
EDIT2 Added lines to MyActivity.java (this solved the problem)
I have preferences set up but have no way to access them. No matter what style I pick in xml and no matter what virtual device or style I pick in Android Studio (AS) 1.1.0, the screen lacks the 3 dots shown below. Not even the pulldown styles that include LightActionBar and DarkActionBar show the dots.
In xml, I've tried <style name="AppBaseTheme" parent="android:Holo.ButtonBar">, which finally worked last night (was having same problem) on a small app, and also, for parent, I tried Base.Theme.AppCompat.Light.DarkActionBar and other things.
I don't so much care if I see the 3 dots; just ANYTHING to expose the preferences screen.
I've also tried never, ifroom, and always for showAsAction:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item android:id="#+id/itemFocus"
android:title="#string/focusAtClue"
android:orderInCategory="200"
app:showAsAction="never"/>
Here's preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
>
<CheckBoxPreference
android:key="#string/focusAfterShow"
android:title="#string/focusAfterShow"
android:summary="Always place the cursor at the 'clue' (sum) after tapping 'Show'."
android:defaultValue="true"
/>
</PreferenceCategory>
<PreferenceCategory
>
<CheckBoxPreference
android:key="#string/screenSaver"
android:title="#string/screenSaver"
android:summary="Keep screen on at all times while running this app."
android:defaultValue="true"
/>
</PreferenceCategory>
</PreferenceScreen>
Here's SettingsFragment.java:
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (key.equalsIgnoreCase("pie_type")){
Log.w("Settings", sharedPref.getString(key, ""));
}
}
}
And SettingsActivity.java:
import android.app.Activity;
import android.os.Bundle;
public class SettingsActivity extends Activity {
public static final String SETTINGS = "com.whatever.kakurocombosbuildvariants.settings";
public static final String FIRST_USE = "com.whateverkakurocombosbuildvariants.firstUse";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
Here's where SettingsActivity is invoked in MyActivity.java:
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MyActivity.java (main activity; 300 LINES OF EXTRANEOUS CODE DELETED)
public class MyActivity extends Activity {
public final String
prefix = "com.XXXX.kakurocombosbuildvariants"
, SETTINGS = prefix + ".settings"
, FIRST_USE = prefix + ".firstUse"
, FOCUS_AT_CLUE = prefix + ".focusAtClue"
, SCREENSAVER = prefix + ".screensaver"
, literally_Focus_At_Clue = "Focus at clue"
, literally_Screen_saver = "Screen saver"
;
public boolean firstUse;
SharedPreferences preferences;
SharedPreferences.Editor editor;
boolean screenSaver;//= false;
boolean focusAtClue ;//= true;
AlertDialog alertDialog;
private void makeActionOverflowMenuShown() {
//devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
popupMessage("Problem making actionbar overflow");
}
}
void showKeypad(){
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
public static boolean isTablet(Context ctx){
return (ctx.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK
)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
#Override public boolean onPrepareOptionsMenu(Menu menu)
{
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setScreensaver()
{
if( ! screenSaver) getWindow().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override protected void
onCreate(Bundle savedInstanceState) // ************************** ON CREATE **********
{
super.onCreate(savedInstanceState);
/////////////////////////// EDIT2 ///////////////////////////////////////
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getWindow().setFormat(Window.FEATURE_ACTION_BAR);
/////////////////////////// EDIT2 ///////////////////////////////////////
if(! FREE) setContentView(R.layout.activity_my);
else setContentView(R.layout.activity_free);
SharedPreferences preferences = getSharedPreferences(SETTINGS, MODE_PRIVATE);
firstUse = preferences.getBoolean(FIRST_USE, true);
if(firstUse){
Toast.makeText(getApplicationContext(), "Welcome to Kakuro Combos", Toast.LENGTH_SHORT).show();
editor = preferences.edit();
editor.putBoolean(FIRST_USE, false);
editor.commit();
}
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() { public void
onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}});
showKeypad();
makeActionOverflowMenuShown();
getWindow().setFormat(Window.FEATURE_ACTION_BAR);
showKeypad();
setScreensaver();
} // onCreate
}
/////////////////////// EDIT2 ////////////////////////////
#Override public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/////////////////////// EDIT2 ////////////////////////////
It looks like main issue is that you're not inflating your menu xml.
Try using ActionBarActivity for your MainActivity, and add onCreateOptionsMenu() in order to inflate the menu xml.
public class MyActivity extends ActionBarActivity{
//...........
#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;
}
//............
}
You need to load the menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<your_menu>, menu);
//...
}
When I access the PreferenceScreen, I notice that my custom switch is off. Then I turn it on and restart the app. I went back to the PreferenceScreen and the switch went back off. This doesn't happen when I use the default SwitchPreference. I am able to customize the SwitchPreference the way I want it to be, so the only problem is the switch value not saving. I have four files related to a customize SwitchPreference and all of the Preferences are placed in an extension of a PreferenceFragment
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings"
>
<com.example.CustomSwitchPreference
android:key="vibration"
android:title="vibration"
android:summary=""
android:defaultValue="true" />
</PreferenceScreen>
CustomSwitchPreference.java:
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected View onCreateView( ViewGroup parent )
{
LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
return li.inflate( R.layout.customswitch_preference, parent, false);
}
/*
#Override
protected void onBindView(View view) {
MainActivity mainActivity = (MainActivity)getContext();
RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame);
Switch s = (Switch)relativeLayout.getChildAt(1);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
persistBoolean(isChecked);
}
});
super.onBindView(view);
}
*/
}
customswitch_preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/switch_title"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentStart="true"/>
<Switch
android:id="#+id/switch_pref"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private ActionBar actionBar;
private boolean mInit = false;
private boolean showIcon = true;
private Menu m;
private GridFragment gridFragment;
private SettingsFragment settingsFragment;
public ImageButton startButton;
public TextView gameTimer;
public TextView mineCount;
public boolean isVibrating;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment = new SettingsFragment();
actionBar = getActionBar();
actionBar.setTitle("Settings");
actionBar.setCustomView(R.layout.actionbar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
startButton.setImageResource(R.drawable.smiley2);
break;
case MotionEvent.ACTION_UP:
restartGame();
break;
}
return false;
}
});
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
TextView textView;
int[] resources =
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r: resources) {
textView = (TextView) findViewById(r);
textView.setTypeface(myTypeface);
}
if (findViewById(R.id.fragment_container) != null){
if (savedInstanceState != null) {
return;
}
}
}
public void restartGame() {
startButton.setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment).commit();
setText(999, gameTimer);
startGame();
}
private void startGame(){
gridFragment = new GridFragment();
gridFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();
}
public void setText(int value, TextView textView){
value = Math.min(999,value);
value = Math.max(-99,value);
textView.setText(String.format("%03d",value));
}
#Override
protected void onStart() {
if (!mInit) {
mInit = true;
Database db = new Database(this);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
m = menu;
return true;
}
private void openSettings(){
showIcon = false;
gridFragment.pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(gridFragment);
ft.add(android.R.id.content, settingsFragment).commit();
//ft.replace(android.R.id.content,settingsFragment);
}
private void updateSettings(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Map<String, ?> map = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
isVibrating = (Boolean)map.get("vibration");
}
private void closeSettings(){
showIcon = true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment).commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
#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) {
openSettings();
return true;
}
else if(id == R.id.backButton){
updateSettings();
closeSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(showIcon);
item = menu.findItem(R.id.backButton);
item.setVisible(!showIcon);
return super.onPrepareOptionsMenu(menu);
}
}
You're never actually setting or saving the state of the switch. You need to override onBindView to set the initial state of the view, and attach a checked change listener to the Switch (R.id.switch_pref) to listen for changes and persist them into SharedPreferences (you can call persistBoolean to do that).