i am a newbie for Android Programming.
Here i have some problem when i want to make an activity (call Category_Setting) that showing list view, but when i switch from main activity to Category_Setting the error report in Android Studio gimme some error like this
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ever_ncn.cashflow/com.example.ever_ncn.cashflow.CategorySetting}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have googling for it, asking some friend, but still i even don't know what is my error for.
Please somebody answer my question with simple understanding words.
Thank You..
NB. here is my code for MainActivity.java
public class MainActivity extends Activity implements OnItemSelectedListener {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
Spinner my_Spinner;
DatabaseHelper dbHelper = new DatabaseHelper(this);
//ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
my_Spinner.setOnItemSelectedListener(this);
select_spinner_Category();
onButtonClickButtonListener();
}
/*ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();*/
/*ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);*/
public void select_spinner_Category () {
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
DatabaseHelper dbH = new DatabaseHelper(getApplicationContext());
List<String> listCategory = dbH.getAllCategory();
ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, listCategory);
adapterCategory
.setDropDownViewResource(android.R.layout.simple_spinner_item);
my_Spinner.setAdapter(adapterCategory);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id){
String label = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "You selected "+label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/*ArrayList<String> arrayCategory;
arrayCategory = dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
ArrayAdapter adapterCategory = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayCategory);
// adapterCategory = new ArrayList<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryList);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
#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;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.CategorySetting");
startActivity(intentAddCateg);
}
}
);
}
#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);
}
}
And this is Category_Setting.java (where i get this error)
public class CategorySetting extends Activity {
private SQLiteDatabase db;
private CursorAdapter currAdapter;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
public void reload(){
listView = (ListView) findViewById(R.id.listViewCateg);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
}
}
);
}
#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_category_setting, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
BtnICancelCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#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);
}
}
In this method in Category_Setting.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
you forgot to load the layout. You should add some code like you used in the MainActivity:
setContentView(R.layout.activity_main);
Right now, the layout is not loaded at all, so
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
will return null.
Related
I am trying to build an app where the user selects date and time (through DatePicker and TimePicker), then presses a button called "Add Exam" which stores these information into a SQLite Database. When the user clicks on "View Exam", the date and time is supposed to show up on the screen along with other information stored in the database.
I get an error with the lines "date.getText().toString(), time1.getText().toString()" where "getText" is not being recognised.
public class Exam extends AppCompatActivity {
DatabaseManager myDb;
EditText un, loc3;
DatePicker date;
TimePicker time1;
int year;
int monthOfYear;
int dayOfMonth;
Button btnAddExam;
Button btnViewExam;
Button btnDeleteExam;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
myDb = new DatabaseManager(this);
un = (EditText)findViewById(R.id.un);
date = (DatePicker)findViewById(R.id.date);
loc3 = (EditText)findViewById(R.id.loc3);
time1 = (TimePicker) findViewById(R.id.time1);
btnAddExam = (Button)findViewById(R.id.addexam);
btnViewExam = (Button)findViewById(R.id.viewexam);
btnDeleteExam = (Button)findViewById(R.id.deleteexam);
AddExam();
ViewExam();
DeleteExam();
}
public void AddExam() {
btnAddExam.setOnClickListener(
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertDataExam(
un.getText().toString(),
loc3.getText().toString(),
date.getText().toString(),
time1.getText().toString()
);
if(isInserted == true)
Toast.makeText(Exam.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Exam.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void ViewExam() {
btnViewExam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllDataExam();
if(res.getCount() == 0) {
message("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Unit Name: "+ res.getString(0)+"\n\n");
buffer.append("Date: "+ res.getString(1)+"\n");
buffer.append("Time: "+ res.getString(2)+"\n");
buffer.append("Location: "+ res.getString(3)+"\n\n");
}
// Show all data
message("Exam Information",buffer.toString());
}
}
);
}
public void DeleteExam() {
btnDeleteExam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
}
public void message(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.screen5_menu, 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.home5) {
Intent intent = new Intent(Exam.this, Home.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You would have to get parts of the date individually
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
See more here
I am having four tab in my View pager I have search in google but I can,t found any solution when Swipe my view pager it work fine like 1-2-3-4 but when I try to swipe reverse 4-3-2-1 than my data get lost or you can say my adapter get lost.My View Pager is inside Activity.My Data is lost when I go to next page and back then back my data is lost.
My Main Activity is:
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
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 boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
My Fragment is
public class ImageListFragment extends Fragment {
String category_Name, Category_ID, Product_ID, Product_Name,
Product_Image, Product_Price, Product_Sale, Cart;
public static final String STRING_IMAGE_URI = "ImageUri";
public static final String STRING_IMAGE_POSITION = "ImagePosition";
private static MainActivity mActivity;
ArrayList<SingleItemModel> singleItemModels;
RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCategoryone();
Fresco.initialize(getContext());
mActivity = (MainActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_recylerview_list, container, false);
return recyclerView;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> {
// private String[] mValues;
private ArrayList<SingleItemModel> mValues;
private RecyclerView mRecyclerView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final SimpleDraweeView mImageView;
public final LinearLayout mLayoutItem;
public final ImageView mImageViewWishlist;
TextView iTemName, itemDescription, itemPrice;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (SimpleDraweeView) view.findViewById(R.id.image1);
mLayoutItem = (LinearLayout) view.findViewById(R.id.layout_item);
mImageViewWishlist = (ImageView) view.findViewById(R.id.ic_wishlist);
iTemName = (TextView) view.findViewById(R.id.itemName);
itemDescription = (TextView) view.findViewById(R.id.itemDescription);
itemPrice = (TextView) view.findViewById(R.id.itemPrice);
}
}
public SimpleStringRecyclerViewAdapter(RecyclerView recyclerView, ArrayList<SingleItemModel> items) {
mValues = items;
mRecyclerView = recyclerView;
}
#Override
public ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder(view);
}
#Override
public void onViewRecycled(ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder) {
if (holder.mImageView.getController() != null) {
holder.mImageView.getController().onDetach();
}
if (holder.mImageView.getTopLevelDrawable() != null) {
holder.mImageView.getTopLevelDrawable().setCallback(null);
//
}
}
#Override
public void onBindViewHolder(final ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder, final int position) {
SingleItemModel singleItemModel = mValues.get(position);
holder.iTemName.setText(singleItemModel.getCategory_Name());
final Uri uri = Uri.parse(singleItemModel.getProduct_Image());
holder.mImageView.setImageURI(uri);
holder.itemPrice.setText(singleItemModel.getProduct_Price());
holder.itemDescription.setText(singleItemModel.getProduct_Sale());
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void getCategoryone() {
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://proaudiobrands.com/app/feature.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("shabina shopping response", response);
try {
singleItemModels = new ArrayList<>();
JSONObject mainObj = new JSONObject(response);
Log.d("shabina ", response);
JSONArray Feature_product = mainObj.getJSONArray("Feature_product");
for (int i = 0; i < Feature_product.length(); i++) {
JSONObject Feature_Product = Feature_product.getJSONObject(i);
String Category_Namee = Feature_Product.getString("Category_Namee");
String Category_IDs = Feature_Product.getString("Category_IDs");
JSONArray Product_List = Feature_Product.getJSONArray("Product_List");
for (int j = 0; j < Product_List.length(); j++) {
JSONObject Category_Name = Product_List.getJSONObject(j);
if (Category_Name.getString("Category_Name").equals("Microphones")) {
category_Name = Category_Name.getString("Category_Name");
Category_ID = Category_Name.getString("Category_ID");
Product_ID = Category_Name.getString("Product_ID");
Product_Name = Category_Name.getString("Product_Name");
Product_Image = Category_Name.getString("Product_Image");
Product_Price = Category_Name.getString("Product_Price");
Product_Sale = Category_Name.getString("Product_Sale");
Cart = Category_Name.getString("Cart");
Log.e("sushil Category_Name", category_Name + " " + Category_ID + " " + Product_ID + " " + Product_Name + " " + Product_Image + " " + Product_Price + " " + Product_Sale + " " + Cart);
SingleItemModel singleItemModel1 = new SingleItemModel(category_Name, Category_ID, Product_ID, Product_Name, Product_Image, Product_Price, Product_Sale, Cart);
singleItemModels.add(singleItemModel1);
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new ImageListFragment.SimpleStringRecyclerViewAdapter(recyclerView, singleItemModels));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("method", "feature");
params.put("userId", "PRO1");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Replace your MainActivity with below
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
viewPager.setOffscreenPageLimit(4);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
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 boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
I'm building an app that uses Google Places Api. Right now, when the user picks a place, the place name is added to a StringSet, which is then (supposed to be) saved to SharedPreferences. However, every time I restart the app, SharedPreferences is cleared. How do I fix this?
public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
placeArrayList = new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, placeArrayList);
placeListView.setAdapter(arrayAdapter);
sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLACE_PICKER_REQUEST = 1;
builder = new PlacePicker.IntentBuilder();
pickPlace();
}
});
}
public void pickPlace(){
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
placeArrayList.add((String) place.getName());
arrayAdapter.notifyDataSetChanged();
Set<String> set = new HashSet<String>();
set.addAll(placeArrayList);
editor.putStringSet("key", set);
sharedPreferences.edit().putStringSet("key", set).apply();
Log.e("places", String.valueOf(sharedPreferences.getStringSet("key", null)));
//Retrieve the values
}
}
}
#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);
}
}
i have a searchview with a listview. i put some items to open a new activity. While im in the first Activity, all right. But if i search another item on Searchview, app obeys the position. Then, wrong item is chosen.
How can i make the item click work by String?
My code:
public class MainActivity extends ListActivity {
ListView lv;
SearchView sv;
String[] teams={"Activity 1","Activity 2","Activity 3","Activity 4","Activity 5","Activity 6"};
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(android.R.id.list);
sv=(SearchView) findViewById(R.id.searchView);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,teams);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
//to open new activity
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (position == 0) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(this, Main3Activity.class);
startActivity(intent);
}
}
}
#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);
}
}
How can i make the item click work by String?
#Override
//to open new activity
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String team = teams[position];
if (team.equalsIgnoreCase("Activity 1")) {
Intent intent = new Intent(this, Activity1.class);
startActivity(intent);
} else if (team.equalsIgnoreCase("Activity 2")) {
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
} //...and so on
}
}
I know that this question is asked many times but we have different situation. Regarding the project I downloaded the project navigation drawer demo from GitHub.com. Provided the code below:
this is the main activity:
package edu.ejapp.dotalegitstore;
#SuppressLint("NewApi")
public class MainActivity extends BaseActivity {
FragmentStackManager fm,sliding_menu;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
setUpView();
menuToggeleSetUp(savedInstanceState);
}
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
sliding_menu.addFragment(new SlidingMenuFragment(), R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
void menuToggeleSetUp(Bundle savedInstanceState){
mDrawerToggle = new ActionBarDrawerToggle(this, drawer,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name
) {
#SuppressLint("NewApi")
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
drawer.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
}
}
#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
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_exit) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("COnfirm exit");
dialog.setMessage("Are you sure you want to exit?");
dialog.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
else if (id == R.id.action_login) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
else {
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The base activity extended by MainActivity:
package edu.ejapp.dotalegitstore;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
#SuppressWarnings("deprecation")
public class BaseActivity extends ActionBarActivity{
public ActionBarDrawerToggle mDrawerToggle;
public DrawerLayout drawer;
CharSequence mDrawerTitle;
CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBar();
}
public void setActionBar(){
getSupportActionBar().setTitle("");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(this.getResources().getColor(R.color.app_main)));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
and lastly the sliding fragment activity, here the on item click is implemented not in baseactivity or main which is the reason of my problem: i cant close the drawer when i clicked item on the drawer:
public class SlidingMenuFragment extends Fragment {
List<String> data;
ListView list_view;
SlidingMenuListAdapter adapter;
#SuppressLint("InflateParams")
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sliding_menu, null);
setUpView(root);
return root;
}
void setUpView(ViewGroup root){
list_view = (ListView)root.findViewById(R.id.list_view);
initList();
setUpClick();
}
void initList(){
data = new ArrayList<String>();
data.add("Home");
data.add("Arcana");
data.add("Courrier");
data.add("Hero Sets");
data.add("Immortals");
adapter = new SlidingMenuListAdapter(getActivity(),data);
list_view.setAdapter(adapter);
}
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"Hi "+position,Toast.LENGTH_SHORT).show();
}
});
}
}
I didnt include the other files such as the xmls. My question is:
How can I close the drawer when I clicked item of the list view provided that the onitemclick is defined in SlidingMenuFragment class and the mDrawerlayout is located in BaseActivity class which is extended by MainActivity class?
create a method to close drawer in your main activity and call it from fragment.
public static void closeDrawer(){
if(drawerLayout.isDrawerOpen(leftDrawerList)){
drawerLayout.closeDrawer(leftDrawerList);
}
}
Inside Fragment
MainActivity.closeDrawer();
here is my suggestion:
provide an interface in SlidingMenuFragment like:
public class SlidingMenuFragment extends Fragment {
private OnListItemClickListener mOnListItemClickListener;
//here is mOnListItemClickListener getter and setter method
public *** set(get)OnListItemClickListener(){};
//define a interface here
public interface OnListItemClickListener{
public void onListenItemClick();
}
.
.
.
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mOnListItemClickListener != null){
mOnListItemClickListener.onListenItemClick();
}
}
});
}
}
and then you should implement this interface in your MainActivity class like:
public class MainActivity extends BaseActivity {
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
SlidingMenuFragment smFragment = new SlidingMenuFragment()
smFragment.setMonListItemClickListener(new OnListItemClickListener(){
public void onListenItemClick(){
drawer.close();
}
});
sliding_menu.addFragment(smFragment, R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
}`