I have this strange bug in my android app. I have one activity with a recycler view and some items in it (in my case there are school subjects four textViews and one framelayout).
When you click on an item a transition with shared elements will be performed and you enter the EditActivity where you can edit the subject. After the transistion finished the text in the editText got shifted up. The Text becomes normal only when you click the editText, i don't know why. Sometimes the text appears normal. Maybe it is because I make a transition from a textView (in the item) to an editText (in the EditActitvty).
Please advise. This is my code.
SubjectActivity.java with RecyclerView:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Learn.sdk21()) {
//To enable window content transitions in your code instead, call the Window.requestFeature() method:
getWindow().requestFeature(android.view.Window.FEATURE_CONTENT_TRANSITIONS);
Transition ts_enter = new Explode(); //Slide(); //Explode();
Transition ts_exit = new ChangeBounds();
ts_enter.setDuration(Learn.animationTime);
ts_exit.setDuration(Learn.animationTime);
/*
If you have set an enter transition for the second activity,
the transition is also activated when the activity starts.
*/
getWindow().setEnterTransition(ts_enter);
getWindow().setExitTransition(ts_exit);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
//Database
dao = new DAO(getApplicationContext());
subjectList = dao.getAllSubjectsAlphabetical();
//Custom Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle(R.string.Subject);
recyclerViewSubject = (RecyclerView) findViewById(R.id.recyclerViewSubject);
setRecyclerViewSubject();
//FloatingActionButton
fabAddSubject = (FloatingActionButton)
findViewById(R.id.fabAddSubject);
fabAddSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddSubjectActivity.class));
}
});
fabAddSubject.attachToRecyclerView(recyclerViewSubject);
}
private void setRecyclerViewSubject() {
//RecyclerView
subjectRecyclerViewAdapter =
new SubjectRecyclerViewAdapter(this, dao.getAllSubjectsAlphabetical());
subjectRecyclerViewAdapter.setClickListener(this);
recyclerViewSubject.setLayoutManager(new LinearLayoutManager(this));
recyclerViewSubject.setAdapter(new ScaleInAnimationAdapter(subjectRecyclerViewAdapter));
}
#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_subject, 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;
} else if (id == android.R.id.home) {
this.finish();
return true;
} else if (id == R.id.debugDelete) {
try {
deleteAll();
} catch (Exception e) {
System.out.println("--> Tried to delete all but: " + e + "<--");
}
return true;
} else if (id == R.id.debugAdd) {
try {
add();
} catch (Exception e) {
System.out.println("--> Tried to delete add5: " + e + "<--");
}
return true;
} else if (id == R.id.refreshSubjectList) {
subjectList = dao.getAllSubjectsAlphabetical();
subjectRecyclerViewAdapter.dataChange(subjectList);
}
return super.onOptionsItemSelected(item);
}
#Override
public void itemClicked(View v, int postion) {
editSubject(v, postion);
}
private void editSubject(View v, int pos) {
Intent intent = new Intent(getApplicationContext(), EditSubjectActivity.class);
intent.putExtra("subjectPos", pos);
if (Learn.sdk21()) {
View view = findViewById(R.id.buttonColor);
Pair<View, String> p1 = Pair.create(v.findViewById(R.id.frameLayoutSubjectColor),
v.findViewById(R.id.frameLayoutSubjectColor).getTransitionName());
Pair<View, String> p2 = Pair.create(v.findViewById(R.id.textViewSubject),
v.findViewById(R.id.textViewSubject).getTransitionName());
Pair<View, String> p3 = Pair.create(v.findViewById(R.id.textViewShort),
v.findViewById(R.id.textViewShort).getTransitionName());
Pair<View, String> p4 = Pair.create(v.findViewById(R.id.textViewRoom),
v.findViewById(R.id.textViewRoom).getTransitionName());
Pair<View, String> p5 = Pair.create(v.findViewById(R.id.textViewTeacher),
v.findViewById(R.id.textViewTeacher).getTransitionName());
Pair<View, String> p6 = Pair.create(findViewById(R.id.fabAddSubject),
findViewById(R.id.fabAddSubject).getTransitionName());
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SubjectActivity.this,
p1, p2, p3, p4, p5, p6);
intent.putExtra("SubjectColor", v.findViewById(R.id.frameLayoutSubjectColor).getTransitionName());
intent.putExtra("SubjectName", v.findViewById(R.id.textViewSubject).getTransitionName());
intent.putExtra("SubjectShort", v.findViewById(R.id.textViewShort).getTransitionName());
intent.putExtra("SubjectRoom", v.findViewById(R.id.textViewRoom).getTransitionName());
intent.putExtra("SubjectTeacher", v.findViewById(R.id.textViewTeacher).getTransitionName());
startActivityForResult(intent, 12, options.toBundle());
} else {
startActivityForResult(intent, 12);
}
}
private void add() {
String[] name = {"Deutsch", "Englisch", "Biologie", "Mathe", "Geschichte",
"Musik", "Physik", "Politik", "Informatik", "Religion"};
String[] nameshort = {"Deu", "Eng", "Bio", "Mat", "Gesch",
"Mus", "Phy", "PoWi", "Info", "Reli"};
String[] room = {"A222", "T292", "B322", "M22", "G666",
"A373", "B888", "C938", "I999", "T666"};
String[] t = {"Test1", "Test2", "Test3", "Test4", "Test5",
"Test6", "Test7", "Test8", "Test9", "Test10"};
String[] c = {"#fff200", "#ff0000", "#ff9000", "#00bbff", "#2aff00",
"#0037ff", "#90ff00", "#00ff4c", "#00ffb2", "#4c00ff"};
for (int i = 0; i < name.length; i++) {
Subject subject = new Subject(name[i], nameshort[i], room[i], t[i], Color.parseColor(c[i]));
dao.addSubject(subject);
}
setRecyclerViewSubject();
}
private void deleteAll() {
int oldSize = dao.getAllSubjects().size();
for (int i = (oldSize - 1); i >= 0; i--) {
int id = dao.getAllSubjects().get(i).getId();
dao.deleteSubject(id);
}
subjectRecyclerViewAdapter =
new SubjectRecyclerViewAdapter(getApplicationContext(), dao.getAllSubjectsAlphabetical());
recyclerViewSubject.setAdapter(new ScaleInAnimationAdapter(subjectRecyclerViewAdapter));
recyclerViewSubject.setLayoutManager(new LinearLayoutManager(this));
subjectRecyclerViewAdapter.notifyItemRangeRemoved(0, dao.getAllSubjects().size());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int subId = data.getIntExtra("subjectId", 0);
int subPos = data.getIntExtra("subjectPos", 0);
int subNewPos = data.getIntExtra("subjectNewPos", subPos);
subjectList = dao.getAllSubjectsAlphabetical();
System.out.print("requestCode" + requestCode
+ "\n" +
"resultCode" + resultCode
+ "\n" +
"subId" + subId
+ "\n" +
"subPos" + subPos
+ "\n" +
"subNewPos" + subNewPos);
if (requestCode == 12) {
if (resultCode == 2) {//Edit
subjectRecyclerViewAdapter.updateItem(subjectList, subPos, subNewPos);
recyclerViewSubject.setAdapter(subjectRecyclerViewAdapter);
} else if (resultCode == 3) {//Delete
subjectRecyclerViewAdapter.removeItem(subjectList, subPos);
recyclerViewSubject.setAdapter(subjectRecyclerViewAdapter);
}
}
}
}
EditSubjectActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Learn.sdk21()) {
//To enable window content transitions in your code instead, call the Window.requestFeature() method:
getWindow().requestFeature(android.view.Window.FEATURE_CONTENT_TRANSITIONS);
Transition ts_enter = new Explode(); //Slide(); //Explode();
Transition ts_exit = new ChangeBounds(); //Slide(); //Explode();
ts_enter.setDuration(Learn.animationTime);
ts_exit.setDuration(Learn.animationTime);
getWindow().setEnterTransition(ts_enter);
getWindow().setExitTransition(ts_exit);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_subject);
//Database
dao = new DAO(getApplicationContext());
//Custom Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
buttonColor = (Button) findViewById(R.id.buttonColor);
buttonColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
colorPickerDialog = new ColorPickerDialog(EditSubjectActivity.this, subject.getColor());
colorPickerDialog.setAlphaSliderVisible(false);
colorPickerDialog.setHexValueEnabled(true);
colorPickerDialog.setTitle("Background");
colorPickerDialog.setOnColorChangedListener(new ColorPickerDialog.OnColorChangedListener() {
#Override
public void onColorChanged(int i) {
subject.setColor(i);
buttonColor.setText("#" + Integer.toHexString(subject.getColor()));
buttonColor.setBackgroundColor(i);
}
});
colorPickerDialog.show();
}
});
//EditText
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
editTextShort = (EditText) findViewById(R.id.editTextShort);
editTextRoom = (EditText) findViewById(R.id.editTextRoom);
editTextTeacher = (EditText) findViewById(R.id.editTextTeacher);
//FAB
fabSaveSubject = (FloatingActionButton) findViewById(R.id.fabSaveSubject);
fabSaveSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSubject();
}
});
fabDeleteSubject = (FloatingActionButton) findViewById(R.id.fabDeleteSubject);
fabDeleteSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSubject();
}
});
setUp();
if(Learn.sdk21()){
Intent intent = getIntent();
editTextSubject.setTransitionName(intent.getStringExtra("SubjectName"));
editTextShort.setTransitionName(intent.getStringExtra("SubjectShort"));
editTextRoom.setTransitionName(intent.getStringExtra("SubjectRoom"));
editTextTeacher.setTransitionName(intent.getStringExtra("SubjectTeacher"));
buttonColor.setTransitionName(intent.getStringExtra("SubjectColor"));
}
}
#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_add_subject, 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;
} else if (id == android.R.id.home) {
finish(1);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish(1);
}
private void saveSubject() {
subject.setSubject(editTextSubject.getText().toString());
subject.setSubjectShort(editTextShort.getText().toString());
subject.setRoom(editTextRoom.getText().toString());
subject.setTeacher(editTextTeacher.getText().toString());
dao.updateSubject(subjectId, subject);
finish(2);
}
private void deleteSubject() {
dao.deleteSubject(subjectId);
finish(3);
}
private void setUp() {
Intent intent = getIntent();
subjectPos = intent.getIntExtra("subjectPos", 0);
subject = dao.getAllSubjectsAlphabetical().get(subjectPos);
subjectId = subject.getId();
editTextSubject.setText(subject.getSubject());
editTextShort.setText(subject.getSubjectShort());
editTextRoom.setText(subject.getRoom());
editTextTeacher.setText(subject.getTeacher());
buttonColor.setText("#" + Integer.toHexString(subject.getColor()));
buttonColor.setBackgroundColor(subject.getColor());
}
private void finish(int i) {
Intent intent = new Intent();
intent.putExtra("subjectPos", subjectPos);
intent.putExtra("subjectId", subjectId);
setResult(i, intent);
switch (i) {
case 1: //Nothing
finishAfterTransition();
break;
case 2: //Edit
int newPos = dao.getSubjectPosition(dao.getAllSubjectsAlphabetical(), subject);
intent.putExtra("subjectNewPos", newPos);
finishAfterTransition();
break;
case 3: //Delete
finish();
break;
}
}
}
SubjectRecyclerViewAdapter.java:
public class SubjectRecyclerViewAdapter
extends RecyclerView.Adapter
<SubjectRecyclerViewAdapter.subjectViewHolder> {
LayoutInflater inflater;
List<Subject> subjectList;
Context context;
ClickListener clickListener;
DAO dao;
public SubjectRecyclerViewAdapter(Context context, List<Subject> subjectList) {
inflater = LayoutInflater.from(context);
this.subjectList = subjectList;
this.context = context;
dao = new DAO(context);
}
#Override
public subjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.subject_item, parent, false);
subjectViewHolder holder = new subjectViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(subjectViewHolder holder, int position) {
Subject subject = subjectList.get(position);
holder.textViewSubject.setText(subject.getSubject());
holder.textViewShort.setText(subject.getSubjectShort());
holder.textViewTeacher.setText(subject.getTeacher());
holder.textViewRoom.setText(subject.getRoom());
holder.frameLayoutSubjectColor.setBackgroundColor(subject.getColor());
if (Learn.sdk21()) {
holder.textViewSubject.setTransitionName("SubjectName_"+position);
holder.textViewShort.setTransitionName("SubjectShort_"+position);
holder.textViewTeacher.setTransitionName("SubjectTeacher_"+position);
holder.textViewRoom.setTransitionName("SubjectRoom_"+position);
holder.frameLayoutSubjectColor.setTransitionName("SubjectColor_" + position);
}
}
#Override
public int getItemCount() {
return subjectList.size();
}
public class subjectViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewSubject,textViewShort, textViewRoom, textViewTeacher;
FrameLayout frameLayoutSubjectColor;
public subjectViewHolder(View itemView) {
super(itemView);
textViewSubject = (TextView) itemView.findViewById(R.id.textViewSubject);
textViewShort = (TextView) itemView.findViewById(R.id.textViewShort);
textViewRoom = (TextView) itemView.findViewById(R.id.textViewRoom);
textViewTeacher = (TextView) itemView.findViewById(R.id.textViewTeacher);
frameLayoutSubjectColor = (FrameLayout) itemView.findViewById(R.id.frameLayoutSubjectColor);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (clickListener != null) {
clickListener.itemClicked(v, getPosition());
}
}
}
public interface ClickListener {
public void itemClicked(View v, int postion);
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
public void removeItem(List<Subject> subjectList, int pos) {
this.subjectList = subjectList;
notifyItemRemoved(pos);
System.out.println("removeItem");
}
public void updateItem(List<Subject> subjectList, int pos, int newPos) {
this.subjectList = subjectList;
notifyItemChanged(pos);
if (pos != newPos) {
notifyItemMoved(pos, newPos);
}
System.out.println("updateItem");
}
public void dataChange(List<Subject> subjectList) {
this.subjectList = subjectList;
notifyDataSetChanged();
System.out.println("dataChange");
}
}
Related
I want to return the data from second activity to first activity using intent when click the OnAddClicked button in second activity, but what I done was not working. The data that I return to first activity is null and I have no idea about this. Can anyone help me to solve this problem?
First Activity:
public class CartView extends AppCompatActivity {
ActivityCartViewBinding binding;
public CartView.MyClickHandler handler;
GridView view_listView;
String Default_curr;
String itemgroup;
String itemtype;
String uprice;
String quantity;
ACDatabase db;
List<AC_Class.Item> s_item = new ArrayList<>();
AC_Class.InvoiceDetails invoiceDetails;
AC_Class.Item item;
String substring = "";
EditText searchEditText;
Button All;
Button Type;
Button Group;
ArrayAdapter<String> adapter;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_cart_view);
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Catalog");
actionBar.setDisplayHomeAsUpEnabled(true);
searchEditText = (EditText) findViewById(R.id.searchField);
UIUtil.hideKeyboard(this);
UIUtil.showKeyboard(this, searchEditText);
db = new ACDatabase(this);
invoiceDetails = new AC_Class.InvoiceDetails();
item = new AC_Class.Item();
handler = new MyClickHandler(this);
binding.setHandler(handler);
All = (Button) findViewById(R.id.button1);
Type = (Button) findViewById(R.id.button2);
Group = (Button) findViewById(R.id.button3);
view_listView = (GridView) findViewById(R.id.GridView);
All.setVisibility(View.GONE);
Type.setVisibility(View.GONE);
Group.setVisibility(View.GONE);
getData("");
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void afterTextChanged(Editable s) {
getData(s.toString().trim());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ctlg_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
/*if (id == android.R.id.home)
{
onBackPressed();
return true;
}*/
if (id == R.id.cart)
{
Intent new_intent = new Intent(CartView.this, CartList.class);
new_intent.putExtra("invoiceDetail", invoiceDetails);
startActivityForResult(new_intent,3);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
getData("");
}
public void getData(String substring) {
Cursor data = db.getItemLike(substring, 0);
if (data.getCount() > 0){
s_item.clear();
while (data.moveToNext()) {
try {
AC_Class.Item item = new AC_Class.Item(data.getString(0), data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5), data.getString(6), data.getString(7), data.getString(8), data.getFloat(9), data.getFloat(10), data.getFloat(11), data.getFloat(12), data.getFloat(13), data.getFloat(14), data.getString(15), data.getString(16), data.getFloat(17), data.getString(18),data.getFloat(19),data.getFloat(20));
s_item.add(item);
} catch (Exception e) { Log.i("custDebug", "error reading image: "+e.getMessage()); }
}
CartViewListAdapter arrayAdapter = new CartViewListAdapter(this, s_item);
view_listView.setAdapter(arrayAdapter);
Cursor dcurren = db.getReg("6");
if(dcurren.moveToFirst()){
Default_curr = dcurren.getString(0);
}
view_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemcode = ((AC_Class.Item)parent.getItemAtPosition(position)).getItemCode();
String uom = ((AC_Class.Item)parent.getItemAtPosition(position)).getUOM();
AC_Class.Item sa =((AC_Class.Item) parent.getItemAtPosition(position));
//Intent item_intent = new Intent();
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//setResult(4, item_intent);
startActivity(item_intent);
//finish();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == 1) {
itemtype = data.getStringExtra("TypeKey");
if (itemtype != null) {
getTypedata();
}
}
break;
case 2:
if (resultCode == 1) {
itemgroup = data.getStringExtra("GroupKey");
if(itemgroup != null){
getGroupdata();
}
}
break;
case 3:
if (resultCode == 1) {
AC_Class.Item i = data.getParcelableExtra("Item");
uprice = data.getStringExtra("Price");
quantity = data.getStringExtra("Quantity");
if (i != null) {
invoiceDetails.setItemCode(i.getItemCode());
invoiceDetails.setItemDescription(i.getDescription());
invoiceDetails.setUPrice(Double.valueOf(i.getPrice()));
invoiceDetails.setUOM(i.getUOM());
//invoiceDetails.setUPrice(Double.valueOf(uprice));
invoiceDetails.setQuantity(Double.valueOf(quantity));
}
}
break;
}
}
}
SecondActivity:
public class ItemDetail extends AppCompatActivity {
ActivityItemDetailBinding binding;
AC_Class.Item items;
AC_Class.ItemUOM itemuom;
AC_Class.Cart cart;
AC_Class.InvoiceDetails invoiceDetails;
ACDatabase db;
String Item;
String ItemUOM;
String Default_curr;
Intent pintent;
EditText etQty;
String default_loc;
List<AC_Class.Item> c_item = new ArrayList<>();
MyClickHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_item_detail);
itemuom = new AC_Class.ItemUOM();
items = new AC_Class.Item();
invoiceDetails = new AC_Class.InvoiceDetails();
cart = new AC_Class.Cart();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
db = new ACDatabase(this);
pintent = getIntent();
//substring = pintent.getStringExtra("substring");
Item = pintent.getStringExtra("ItemKey");
ItemUOM = pintent.getStringExtra("ItemUOMKey");
handler = new MyClickHandler(this);
binding.setHandler(handler);
Cursor loc = db.getReg("7");
if(loc.moveToFirst()){
default_loc = loc.getString(0);
}
items = pintent.getParcelableExtra("Items");
binding.setItem(items);
binding.setInvoicedetail(invoiceDetails);
binding.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
etQty = (EditText)findViewById(R.id.quantity);
String qty = etQty.getText().toString();
if(qty.length() > 0)
{
invoiceDetails.setQuantity(Double.valueOf(qty));
//Calculation();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}
public class MyClickHandler {
Context context;
public MyClickHandler(Context context) {
this.context = context;
}
public void OnAddClicked(View view) {
//Intent new_intent = new Intent(context, CartList.class);
Intent new_intent = new Intent(context,CartView.class);
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(1, new_intent);
finish();
}
}
}
OnAddClicked your are finishing the activity when it goes to next activity previous activity goes to end....so remove the finish();
First thing first, to get result from other activity, you need to Use startActivityForResult method instead of startActivity.
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//startActivity(item_intent);
startActivityForResult(item_intent,REQUST_CODE);
and for setting result
Intent new_intent = new Intent();
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(Activity.RESULT_OK, new_intent);
finish();
and to receive result use below code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(REQUST_CODE==requestCode && resultCode==Activity.RESULT_OK){
// do logical stuff.
}
}
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);
}
}
}
Everything works fine, except that when I try to search on my app, it crashes. The problem is in the method onQueryTextChange, please help me to fix it:
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private static final int REQUEST_CAMERA_PERMISSION = 200;
Button goSettings;
ListView listApps;
Context context;
Button go_AndroBooster,goPerms,lockAll,unlockAll,goLogs;
Intent i;
private AccountHeader headerResult = null;
private Drawer result = null;
private MiniDrawer miniResult = null;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
MaterialProgressBar loadingBar;
ColorManager colorManager;
RelativeLayout mainLayout;
ArrayList<ApplicationInfo> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
colorManager = new ColorManager(this);
setSupportActionBar(toolbar);
mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
packageManager = getPackageManager();
listApps = (ListView) findViewById(R.id.listApps);
go_AndroBooster = (Button) findViewById(R.id.go_booster);
goPerms = (Button) findViewById(R.id.goPerms);
lockAll = (Button) findViewById(R.id.lock_all);
unlockAll = (Button) findViewById(R.id.unlock_all);
loadingBar = (MaterialProgressBar) findViewById(R.id.loadingBar);
goLogs = (Button) findViewById(R.id.goLogs);
goSettings = (Button) findViewById(R.id.lockSettings);
listApps.setItemsCanFocus(true);
startLockService();
setSupportActionBar(toolbar);
//set the back arrow in the toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#25517d")));
final IProfile profile2 = new ProfileDrawerItem().withIcon(R.drawable.user_icon);
// Create the AccountHeader
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withTranslucentStatusBar(false)
.withHeaderBackground(R.drawable.header)
.addProfiles(profile2)
.build();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withDrawerLayout(R.layout.crossfade_material_drawer)
.withHasStableIds(true)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.Home).withIcon(R.drawable.homee).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.logs).withIcon(R.drawable.cleanapp).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.resetpass).withIcon(R.drawable.boost).withIdentifier(3),
new PrimaryDrawerItem().withName(R.string.language).withIcon(R.drawable.share).withIdentifier(4),
new PrimaryDrawerItem().withName(R.string.share).withIcon(R.drawable.rate).withIdentifier(6),
new PrimaryDrawerItem().withName(R.string.rate).withIcon(R.drawable.rate).withIdentifier(7)
// new DividerDrawerItem(),
// new SecondaryDrawerItem().withName(R.string.drawer_item_seventh).withIcon(FontAwesome.Icon.faw_github).withIdentifier(7).withSelectable(false)
) // add the items we want to use with our Drawer
.withSelectedItemByPosition(1)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (drawerItem.getIdentifier() == 1) {
// Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 2) {
i = new Intent(getApplicationContext(), LogsActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 3) {
i = new Intent(getApplicationContext(), SetLockTypeActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 4) {
LanguagesDialog languagesDialog = new LanguagesDialog();
languagesDialog.show(getFragmentManager(), "LanguagesDialogFragment");
} else if (drawerItem.getIdentifier() == 6) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id="
+ getPackageName());
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, getResources().getText(R.string.shareusing)));
result.closeDrawer();
}else if (drawerItem.getIdentifier() == 7) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName()));
startActivity(browserIntent);
result.closeDrawer();
}
//
//
return false;
}
})
.withSavedInstance(savedInstanceState)
.withShowDrawerOnFirstLaunch(false)
.build();
//get out our drawerLyout
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
//hook to the crossfade event
crossfadeDrawerLayout.withCrossfadeListener(new CrossfadeDrawerLayout.CrossfadeListener() {
#Override
public void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset) {
Log.e("CrossfadeDrawerLayout", "crossfade: " + currentSlidePercentage + " - " + slideOffset);
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startReqUsageStat();
}
}, 3000);
lockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.lockAllApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
unlockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.resetLockedApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
goPerms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RequestPermission.class);
startActivity(i);
}
});
goLogs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LogsActivity.class);
startActivity(i);
}
});
go_AndroBooster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startApplication("");
}
});
goSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
finish();
}
});
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
new LoadApplications().execute();
}
}, 1500);
new Thread(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
}
}).start();
}
#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);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
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();
return super.onOptionsItemSelected(item);
}
private void startLockService() {
if (!isMyServiceRunning(LockService.class)){
context.startService(new Intent(context, LockService.class));
}
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
private void startReqUsageStat(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission()){
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Toast.makeText(context,getString(R.string.please_give_usage_Stats),Toast.LENGTH_LONG).show();
}
}
} public boolean checkUsageStatsPermission(){
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
return !queryUsageStats.isEmpty();
}
public void startApplication(String packageName)
{
try
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info : resolveInfoList)
if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
{
launchComponent(info.activityInfo.packageName, info.activityInfo.name);
return;
}
showInMarket(packageName);
}
catch (Exception e)
{
showInMarket(packageName);
}
}
public String getPattern() {
File file = new File("/data/data/com.project.applocker/files/pattern");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
Log.d("okuma hatası", "no 1");
}
return text.toString();
}
private void launchComponent(String packageName, String name)
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(packageName, name));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showInMarket(String packageName)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final List<ApplicationInfo> appsList = context.getPackageManager().getInstalledApplications(0);
final ApplicationInfo data = appsList.get(i);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.performClick();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
private class LoadApplications extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
if(!isMyServiceRunning(LockService.class)){
startLockService();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
listApps.setAdapter(listadaptor);
listApps.setOnItemClickListener(MainActivity.this);
loadingBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
loadingBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
startLockService();
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (!info.packageName.equals("com.google.android.googlequicksearchbox")) {
if (!info.packageName.equals("com.project.applocker")) {
if (!info.packageName.contains("launcher3")) {
if (!info.packageName.contains("launcher")) {//com.google.android.googlequicksearchbox
if (!info.packageName.contains("trebuchet")) {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
}
Adapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
List<String> allAppList = null;
List<String> lockedAppList = null;
ColorManager colorManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appList) {
super(context, textViewResourceId, appList);
this.context = context;
allAppList = new ArrayList<String>();
colorManager = new ColorManager(context);
lockedAppList = new ArrayList<String>();
this.appsList = appList;
packageManager = context.getPackageManager();
preferences=context.getSharedPreferences("chosen_apps", context.MODE_PRIVATE);
Collections.sort(appsList, new ApplicationInfo.DisplayNameComparator(packageManager));
editor = preferences.edit();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.app_list_item, null);
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
CardView cardViewApps = (CardView) view.findViewById(R.id.cardViewApps);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
if(preferences.getBoolean(data.packageName,false)){
lockApp.setChecked(true);
}
else{
lockApp.setChecked(false);
}
lockApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.stopService(new Intent(context, LockService.class));
if (lockApp.isChecked()){
Log.d("tıklanmış",""+data.packageName);
editor.putBoolean(data.packageName,true).apply();
}
if (!lockApp.isChecked()){
Log.d("silinmiş",""+data.packageName);
editor.putBoolean(data.packageName,false).apply();
}
context.startService(new Intent(context, LockService.class));
}
});
}
return view;
}
private void startLockService() {
context.startService(new Intent(context, LockService.class));
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
}
The problem is here:
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
I think your method should be like below
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
}
if(templist != null && templist.size() > 0){}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,templist);
listApps.setAdapter(adapter);
}else{
listApps.setAdapter(null);
}
return true;
};
The Reason is the interstitial ad is on wrong way.
Can someone tell me Is there a problem with my interstitial?
Where to put it?
My code from where interstitial is:
public class ActivityMain extends Activity implements OnItemClickListener,
onWelComeButtonClickListener, OnClickListener {
MatrixCursor cursor;
ActionBar actionBar;
DrawerLayout dLayout;
ListView channelListView;
ChannelCustomAdapter adapter;
ActionBarDrawerToggle toggle;
CharSequence title;
Bundle bundle;
Menu menu;
RelativeLayout rlDrawerOpen;
Typeface selectFonts;
TextView tFacebook, tRateus;
AdRequest fullScreenAdRequest;
InterstitialAd fullScreenAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializer();
dLayout.setDrawerListener(toggle);
channelListView.setOnItemClickListener(this);
tFacebook.setOnClickListener(this);
tRateus.setOnClickListener(this);
enableAd();
}
private void enableAd() {
// adding full screen add
fullScreenAdd = new InterstitialAd(this);
fullScreenAdd.setAdUnitId("a151b7d316a5c1d");
fullScreenAdRequest = new AdRequest.Builder().build();
fullScreenAdd.loadAd(fullScreenAdRequest);
fullScreenAdd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.i("FullScreenAdd", "Loaded successfully");
fullScreenAdd.show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Log.i("FullScreenAdd", "failed to Load");
}
});
}
private void initializer() {
actionBar = getActionBar();
selectFonts = (Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Bold.ttf"));
dLayout = (DrawerLayout) findViewById(R.id.dl_drawerLayout);
rlDrawerOpen = (RelativeLayout) findViewById(R.id.rl_drawer_open);
channelListView = (ListView) findViewById(R.id.lv_channel_List);
title = getResources().getString(R.string.app_name);
tFacebook = (TextView) findViewById(R.id.tvFacbook);
tRateus = (TextView) findViewById(R.id.tvRateUs);
adapter = new ChannelCustomAdapter(this, GlobalData.getInstance()
.getArrChannels());
channelListView.setAdapter(adapter);
toggle = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_drawer,
R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView) {
setTitle("Select Channel");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
setTitle(title);
invalidateOptionsMenu();
}
};
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// use the query to search your data somehow
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG)
.show();
} else {
fragmentSelector();
}
}
private void fragmentSelector() {
bundle = getIntent().getBundleExtra("BUNDLE");
if (bundle == null) {
Fragment fr = new WelcomeFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
setTitle(title);
((WelcomeFragment) fr).setOnWelComeButtonClickListener(this);
} else {
selectItem(bundle.getInt("POS"));
setTitle(bundle.getString("NAME"));
}
}
public void selectItem(int position) {
Fragment fr = new RadioFragment();
bundle = new Bundle();
bundle.putString("URL",
GlobalData.getInstance().getArrChannels().get(position)
.getUrl());
bundle.putString("NAME",
GlobalData.getInstance().getArrChannels().get(position)
.getChannelName());
bundle.putInt("POS", position);
fr.setArguments(bundle);
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
title = GlobalData.getInstance().getArrChannels().get(position)
.getChannelName();
dLayout.closeDrawer(rlDrawerOpen);
}
#Override
public void setTitle(CharSequence title) {
actionBar.setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (getPositionfromString(query) != -1) {
Intent intent = new Intent(ActivityMain.this,
RadioService.class);
stopService(intent);
selectItem(getPositionfromString(query));
setTitle(query);
} else {
Toast.makeText(getApplicationContext(), "No channel found",
Toast.LENGTH_LONG).show();
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
String[] columnNames = {
"_id", "text"
};
cursor = new MatrixCursor(columnNames);
String[] temp = new String[2];
// int id = 0;
for (int i = 0; i < GlobalData.getInstance().getArrChannels()
.size(); i++) {
if (GlobalData.getInstance().getArrChannels().get(i)
.getChannelName().toLowerCase()
.contains(newText.toLowerCase())) {
temp[0] = Integer.toString(i);
temp[1] = GlobalData.getInstance().getArrChannels()
.get(i).getChannelName();
cursor.addRow(temp);
}
}
String[] from = {
"text"
};
int[] to = {
R.id.text
};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
ActivityMain.this, R.layout.search_item, cursor, from,
to, SimpleCursorAdapter.NO_SELECTION);
searchView.setSuggestionsAdapter(cursorAdapter);
return true;
}
});
searchView.setOnSuggestionListener(new OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(1), true);
return false;
}
});
return true;
}
private int getPositionfromString(String chn) {
for (int i = 0; i < GlobalData.getInstance().getArrChannels().size(); i++) {
if (chn.contentEquals(GlobalData.getInstance().getArrChannels()
.get(i).getChannelName())) {
return i;
}
}
return -1;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (toggle.onOptionsItemSelected(item)) return true;
if (item.getItemId() == R.id.search) return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.search).setVisible(!dLayout.isDrawerOpen(rlDrawerOpen));
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView <? > parent, View view, int position,
long id) {
Intent intent = new Intent(ActivityMain.this, RadioService.class);
stopService(intent);
selectItem(position);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onWelComeButtonClick() {
dLayout.openDrawer(rlDrawerOpen);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvFacbook:
Intent i = new Intent(ActivityMain.this, ShowFacebook.class);
startActivity(i);
break;
case R.id.tvRateUs:
String linkurl = "http://play.google.com/store/apps/details?id=com.global.danceradio";
if (linkurl != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, linkurl);
shareIntent.setType("text/plain");
startActivity(shareIntent);
} else {
Toast.makeText(getApplicationContext(), "Sharing failed...",
Toast.LENGTH_LONG).show();
}
break;
}
}
}
Here, everything looks normal. But there is no the rest of the code. Maybe you create an activity every second.
I would recommend you to write in support of the admob and clarify the issues. Maybe you're lucky and they will unblock you.
https://support.google.com/admob/answer/6201362?hl=en
Check admob support. they updated new photos for better explanation.