Ussd code does not work properly - java

I have a ussd code on a button.I add CALL_PHONE permissions in manifest.
I use the api (23).
This code does not work properly
Basically what I should do?Thanks.
I have following error:
?E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mahdishekari.mycollectbill, PID: 31738
java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{4e2904f 31738:com.mahdishekari.mycollectbill/u0a109} (pid=31738, uid=10109) with revoked permission android.permission.CALL_PHONE
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2776)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1509)
at android.app.Activity.startActivityForResult(Activity.java:3958)
at android.app.Activity.startActivityForResult(Activity.java:3919)
at com.mahdishekari.mycollectbill.ActivityMain$C00661.onClick(ActivityMain.java:78)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:21349)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
I/Process: Sending signal. PID: 31738 SIG: 9
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
My code:
public class ActivityMain extends ActivityBase {
Button btnLink;
Button btnPayBill;
Button btnRecords;
Button btnScanner;
Button btnSupport;
boolean doubleBackToExitPressedOnce;
DatabaseHelper2 myDbHelper;
TextView tvBillType;
TextView tvPrice;
EditText txtBillID;
EditText txtPayID;
EditText txtPrice;
class C00661 implements OnClickListener {
C00661() {
}
public void onClick(View v) {
String payID = ActivityMain.this.txtPayID.getText().toString();
String billID = ActivityMain.this.txtBillID.getText().toString();
String myID = "124336";
String price = ActivityMain.this.txtPrice.getText().toString();
if (billID.length() == 0) {
ActivityMain.this.showToast("\u0634\u0646\u0627\u0633\u0647 \u0642\u0628\u0636 \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else if (payID.length() == 0) {
ActivityMain.this.showToast("\u0634\u0646\u0627\u0633\u0647 \u067e\u0631\u062f\u0627\u062e\u062a \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else if (price.length() == 0) {
ActivityMain.this.showToast("\u0645\u0628\u0644\u063a \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else {
int i;
int payIdLen = payID.length();
for (i = 0; i < 13 - payIdLen; i++) {
payID = "0" + payID;
}
int billIdLen = billID.length();
for (i = 0; i < 13 - billIdLen; i++) {
billID = "0" + billID;
}
Bill entityBillRercord = new Bill();
entityBillRercord.billId = billID;
entityBillRercord.createDate = Tools.getDate();
entityBillRercord.payId = payID;
entityBillRercord.refId = "";
entityBillRercord.price = Tools.toInt(price);
DbBills.insert(entityBillRercord);
String encodeHash = Uri.encode("#");
String ussd = "*733*3*2*" + billID + "*" + payID + "*" + encodeHash;
ActivityMain.this.startActivityForResult(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussd)),1);
}
}
}
class Scanner implements OnClickListener {
Scanner() {
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnReadBarcode) {
IntentIntegrator scanIntegrator = new IntentIntegrator(ActivityMain.this);
scanIntegrator.initiateScan();
}
}
}
class C00683 implements OnClickListener {
C00683() {
}
public void onClick(View v) {
Intent intent = new Intent(ActivityMain.this, ActivitySupport.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
class C00694 implements OnClickListener {
C00694() {
}
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("android.intent.extra.SUBJECT", "\u0646\u0631\u0645 \u0627\u0641\u0632\u0627\u0631 \u0647\u0645\u0647 \u0642\u0628\u0636");
intent.putExtra("android.intent.extra.TEXT", "\u0646\u0631\u0645 \u0627\u0641\u0632\u0627\u0631 \u0647\u0645\u0647 \u0642\u0628\u0636\n\r\u067e\u0631\u062f\u0627\u062e\u062a \u0631\u0627\u062d\u062a \u0648 \u0622\u0633\u0627\u0646 \u06a9\u0644\u06cc\u0647 \u0642\u0628\u0648\u0636 \u0645\u062c\u0647\u0632 \u0628\u0647 \u0628\u0627\u0631\u06a9\u062f \u062e\u0648\u0627\u0646\n\r http://yealame.ir/upload/allbills.apk");
ActivityMain.this.startActivity(Intent.createChooser(intent, "share"));
}
}
class C00705 implements OnClickListener {
C00705() {
}
public void onClick(View v) {
Intent intent = new Intent(ActivityMain.this, ActivityRecords.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
class C00716 implements TextWatcher {
C00716() {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
String payID = ActivityMain.this.txtPayID.getText().toString();
String price = "";
if (payID.length() != 0) {
int i;
int payIdLen = payID.length();
for (i = 0; i < 13 - payIdLen; i++) {
payID = "0" + payID;
}
for (i = 0; i < 8; i++) {
price = new StringBuilder(String.valueOf(price)).append(String.valueOf(payID.charAt(i))).toString();
}
price = String.valueOf(Tools.toInt(price));
ActivityMain.this.txtPrice.setText(new StringBuilder(String.valueOf(price)).append("00").toString());
ActivityMain.this.tvPrice.setText("\u0645\u0628\u0644\u063a \u0642\u0628\u0636: " + price + "00 \u062a\u0648\u0645\u0627\u0646");
}
}
}
class C00727 implements TextWatcher {
C00727() {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
String billID = ActivityMain.this.txtBillID.getText().toString();
int billIdLen = billID.length();
if (billIdLen != 0) {
for (int i = 0; i < 13 - billIdLen; i++) {
billID = "0" + billID;
}
ActivityMain.this.setBillIcon(Tools.getBillIcon(billID));
}
}
}
class C00738 implements Runnable {
C00738() {
}
public void run() {
ActivityMain.this.doubleBackToExitPressedOnce = false;
}
}
public ActivityMain() {
this.doubleBackToExitPressedOnce = false;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(1);
setContentView(R.layout.main);
setFont(findViewById(R.id.llMain));
loadDb();
this.btnPayBill = (Button) findViewById(R.id.btnPay);
this.btnScanner = (Button) findViewById(R.id.btnReadBarcode);
this.txtPayID = (EditText) findViewById(R.id.txtPayID);
this.txtPrice = (EditText) findViewById(R.id.txtPrice);
this.txtBillID = (EditText) findViewById(R.id.txtBillID);
this.tvPrice = (TextView) findViewById(R.id.tvBillPrice);
this.tvBillType = (TextView) findViewById(R.id.tvBillType);
this.btnRecords = (Button) findViewById(R.id.btnRecords);
this.btnLink = (Button) findViewById(R.id.btnLink);
this.btnSupport = (Button) findViewById(R.id.btnSupport);
setListeners();
}
private void loadDb() {
this.myDbHelper = new DatabaseHelper2(this);
try {
this.myDbHelper.createDataBase();
} catch (IOException e) {
}
try {
this.myDbHelper.openDataBase();
} catch (SQLException e2) {
}
BaseDataLayer.db = this.myDbHelper.getDB();
}
private void setListeners() {
this.btnPayBill.setOnClickListener(new C00661());
this.btnScanner.setOnClickListener(new Scanner());
this.btnSupport.setOnClickListener(new C00683());
this.btnLink.setOnClickListener(new C00694());
this.btnRecords.setOnClickListener(new C00705());
this.txtPayID.addTextChangedListener(new C00716());
this.txtBillID.addTextChangedListener(new C00727());
}
private void setBillIcon(int billType) {
switch (billType) {
case CursorAdapter.FLAG_AUTO_REQUERY /*1*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_1_waterpng);
case CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER /*2*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_2_electric);
case TransportMediator.FLAG_KEY_MEDIA_FAST_FORWARD /*3*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_3_gas);
case TransportMediator.FLAG_KEY_MEDIA_PLAY /*4*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_4_tel);
default:
this.tvBillType.setBackgroundDrawable(null);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
int contentsLen = scanContent.length();
for (int i = 0; i < 26 - contentsLen; i++) {
scanContent = "0" + scanContent;
}
if (scanContent != null) {
String txtBillID = scanContent.substring(0, 13);
String txtPayID = scanContent.substring(18);
this.txtBillID.setText(txtBillID);
this.txtPayID.setText(txtPayID);
this.btnPayBill.setActivated(true);
}
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
public void onBackPressed() {
if (this.doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "\u0628\u0631\u0627\u06cc \u062e\u0631\u0648\u062c \u062f\u0648\u0628\u0627\u0631\u0647 \u06a9\u0644\u06cc\u062f \u0628\u0627\u0632\u06af\u0634\u062a \u0631\u0627 \u0628\u0632\u0646\u06cc\u062f", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new ActivityMain.C00738(), 2000);
}

In android > 23 you must check permission at runtime
Requesting Permissions at Run Time

In the Manifest you have declared that you will be requesting those permissions from the user. But, you must understand that you haven't actually obtained those permissions just by declaring them in the Manifest. You need to Request for those permissions during runtime.
Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. So even if the app used the camera yesterday, it can't assume it still has that permission today.
Source: Official Website
I haven't gone through your code completely. However, with regards to solving the error you have posted, the solution is pretty simple. All you need to do is to ask for android.permission.CALL_PHONE during runtime.
The best guide would probably be the official website. It's just a 10-minute read.

Related

How to add images from realtime database in every question?

Question Model-
public class QuestionModel {
private String Id;
private String question;
private String A;
private String B;
private String C;
private String D;
private String answer;
private String link;
private String set;
public QuestionModel(String id, String question, String a, String b, String c, String d, String answer, String set, String link) {
Id = id;
this.question = question;
A = a;
B = b;
C = c;
D = d;
this.answer = answer;
this.set = set;
this.link = link;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getA() {
return A;
}
public void setA(String a) {
A = a;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
public String getD() {
return D;
}
public void setD(String d) {
D = d;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Question Activity -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
Toolbar toolbar = findViewById(R.id.toolbar);
broadcastReceiver = new ConnectionReceiver();
setSupportActionBar(toolbar);
question = findViewById(R.id.question);
noindicator = findViewById(R.id.no_indicator);
bookmark1btn = findViewById(R.id.bookmark_btn1);
optioncontainer = findViewById(R.id.options_containers);
sharebtn = findViewById(R.id.share_btn);
nextbtn = findViewById(R.id.next_btn);
image =findViewById(R.id.imageView);
preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
editor=preferences.edit();
gson =new Gson();
setId = getIntent().getStringExtra("setId");
loadingDialog = new Dialog(this);
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.round_corner));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
list = new ArrayList<>();getBookmarks();
bookmark1btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (modelmatch()){
bookmarksList.remove(matchedQuestionPosition);
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}else {
bookmarksList.add(list.get(position));
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark));
}
}
});
setId = getIntent().getStringExtra("setId");
loadingDialog = new Dialog(this);
loadingDialog.setContentView(R.layout.loading);
loadingDialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.round_corner));
loadingDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
loadingDialog.setCancelable(false);
list = new ArrayList<>();
loadingDialog.show();
myRef.child("SETS").child(setId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String id = dataSnapshot1.getKey();
String question = dataSnapshot1.child("question").getValue().toString();
String a = dataSnapshot1.child("optionA").getValue().toString();
String b = dataSnapshot1.child("optionB").getValue().toString();
String c = dataSnapshot1.child("optionC").getValue().toString();
String d = dataSnapshot1.child("optionD").getValue().toString();
String correctANS = dataSnapshot1.child("correctAns").getValue().toString();
String link = dataSnapshot1.child("imageurl").getValue().toString();
if(!link.equals("https://firebasestorage.googleapis.com/v0/b/bcs-bangla-c2aa0.appspot.com/o/line1.png?alt=media&token=4ff22c6f-edd9-4571-844e-70612d066296"))
{
Picasso.get().load(link).into(image);
}
else
{
Picasso.get().load(https://firebasestorage.googleapis.com/v0/b/bcs-bangla-c2aa0.appspot.com/o/line1.png?alt=media&token=4ff22c6f-edd9-4571-844e-70612d066296).into(image);
}
list.add(new QuestionModel(id,question,a,b,c,d,correctANS,setId,link));
}
if (list.size() > 0){
for (int i = 0; i < 4; i++){
optioncontainer.getChildAt(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer((Button)v);
}
});
}
playAmin(question,0,list.get(position).getQuestion());
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextbtn.setEnabled(false);
nextbtn.setAlpha(0.7f);
enableoption(true);
position++;
if (position == list.size()){
////score activity
if (interstitialAd.isLoaded()){
interstitialAd.show();
return;
}
Intent scoreIntent =new Intent(QuestionActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",score);
scoreIntent.putExtra("total",list.size());
startActivity(scoreIntent);
finish();
return;
}
count = 0;
playAmin(question,0,list.get(position).getQuestion());
}
});
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String body = list.get(position).getQuestion() + "\n (A) " +
list.get(position).getA() + "\n (B) " +
list.get(position).getB() + "\n (C) " +
list.get(position).getC() + "\n (D) " +
list.get(position).getD();
Intent shareaintent = new Intent(Intent.ACTION_SEND);
shareaintent.setType("text/plain");
shareaintent.putExtra(Intent.EXTRA_SUBJECT, "QUIZ CHALLANGE");
shareaintent.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(shareaintent,"share via"));
}
});
}else {
finish();
Toast.makeText(QuestionActivity.this,"no question",Toast.LENGTH_SHORT).show();
}
loadingDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(QuestionActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
finish();
}
});
}
protected void onPause(){
super.onPause();
storebookmarks();
}
private void playAmin (final View view, final int Value, final String data){
for (int i = 0; i < 4; i++){
optioncontainer.getChildAt(i).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FFCFFFD1")));
}
view.animate().alpha(Value).scaleX(Value).scaleY(Value).setDuration(500).setStartDelay(100)
.setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
if (Value == 0 && count < 4){
String option = "";
if (count == 0){
option = list.get(position).getA();
}else if (count == 1){
option = list.get(position).getB();
}else if (count == 2){
option = list.get(position).getC();
}else if (count == 3){
option = list.get(position).getD();
}
playAmin(optioncontainer.getChildAt(count),0,option);
count++;
}
}
#Override
public void onAnimationEnd(Animator animation) {
////Data change
if (Value == 0){
try {
((TextView) view).setText(data);
noindicator.setText(position+1+"/"+list.size());
if (modelmatch()){
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark));
}else {
bookmark1btn.setImageDrawable(getDrawable(R.drawable.bookmark_border));
}
}catch (ClassCastException ex){
((Button) view).setText(data);
}
view.setTag(data);
playAmin(view,1,data);
}else {
enableoption(true);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private void checkAnswer(Button selectedOption){
enableoption(false);
nextbtn.setEnabled(true);
nextbtn.setAlpha(1);
if (selectedOption.getText().toString().equals(list.get(position).getAnswer())){
////correct ans
score++;
selectedOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4CAF50")));
//Toast.makeText(QuestionActivity.this,score,Toast.LENGTH_SHORT).show();
}else {
///incorrect ans
selectedOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FF0000")));
Button correctOption = (Button) optioncontainer.findViewWithTag(list.get(position).getAnswer());
correctOption.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#4CAF50")));
}
}
private void enableoption(boolean enable){
for (int i = 0;i < 4;i++){
optioncontainer.getChildAt(i).setEnabled(enable);
if (enable){
optioncontainer.getChildAt(i).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FFCFFFD1")));
}
}
}
private void getBookmarks(){
String json= preferences.getString(KEY_NAME,"");
Type type = new TypeToken<List<QuestionModel>>(){}.getType();
bookmarksList = gson.fromJson(json, type);
if (bookmarksList == null){
bookmarksList = new ArrayList<>();
}
}
private boolean modelmatch(){
boolean matched = false;
int i = 0;
for (QuestionModel model : bookmarksList){
if (model.getQuestion().equals(list.get(position).getQuestion())
&& model.getAnswer().equals(list.get(position).getAnswer())
&& model.getSet().equals(list.get(position).getSet())){
matched = true;
matchedQuestionPosition = i;
}
i++;
}
return matched;
}
private void storebookmarks(){
String json = gson.toJson(bookmarksList);
editor.putString(KEY_NAME,json);
editor.commit();
}
protected void registoreNetworkBroadcast(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
registerReceiver(broadcastReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregistorNetwork(){
try{
unregisterReceiver(broadcastReceiver);
}catch(IllegalArgumentException e){
e.printStackTrace();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
unregistorNetwork();
}
private void loadAds(){
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getResources().getString(R.string.interstitialAd_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd
.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
interstitialAd.loadAd(new AdRequest.Builder().build());
Intent scoreIntent =new Intent(QuestionActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",score);
scoreIntent.putExtra("total",list.size());
startActivity(scoreIntent);
finish();
return;
}
});
}
}
There are Question Activity of a quiz app. Here I want to show different image from firebase in every question for the quiz app. I have tried to show image.I have added imageurl in QuestionModel and tried to show using picasso library.But it did not worked.In every question same image shown although i have added different links of image(which i have stored in firebase storage and added the link in question in firebase) in firebase but with every question is shows the same image . Please help me to do this.

duplicate actions in android application when going to home screen

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

How to record dynamically generated buttons into the SQLite database

I'm building an app where a user dynamically generates semesters (buttons) through the Java code. Let's say that the user generates about 4 buttons (the user can generate up to 8), I want to store that into the SQLite database I've created. This is my first app ever and likely, my first time using an SQLite database. I went through the SQLite Android tutorials but my app is a bit different compared to the examples they were working with.
What I need help with, is to be able to store the dynamically generated buttons into my database so I have the exact same amount saved next time the app is launched again. I also need to wire the delete (menuItem and alertdialog) function with the onUpgrade.
This is my Mainactivity.java. This is where all my UI generation takes place. Its also my homepage.
public class MainActivity extends AppCompatActivity {
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout) findViewById(R.id.semester_grid_layout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for (int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterGridLayout.getChildCount() > 0) {
semesterGridLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterLayout.getChildCount() > 0) {
semesterLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
}
counter = 0;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x) / 3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
setOnClickListenerForSemesterButton(counter);
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
} else if (counter == 0) {
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnClickListenerForSemesterButton(int id){
semesterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SemesterBuilderActivity.class);
intent.putExtra("someKey", 1);
startActivity(intent);
}
});
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
This is my Contract class:
public final class SemesterContract {
private SemesterContract(){}
public static final class SemesterEntry implements BaseColumns{
public static final String TABLE_NAME = "semesters";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_SEMESTER_NAME = "semester";
}
}
And finally this is my database helper:
public class SemesterDBHelper extends SQLiteOpenHelper{
public SemesterDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public static final String DATABASE_NAME = "semesters.db";
public static final int DATABASE_VERSION = 1;
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
+ SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL";
db.execSQL(SQL_CREATE_SEMESTER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I appreciate all of the help.

[HELP]FATAL EXCEPTION: main java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
I think string may be null somewhere. Please type something in textfield or check for null string.

Fatal runtime error at android.media.audiofx.Equalizer.<init>

I am working on equalier app and no errors in code at all. when I run app on phone it force closes, I logcat and this is result
03-22 02:49:17.945: E/AndroidRuntime(4318): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
03-22 02:50:34.796: E/AndroidRuntime(4423): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
I tried on android gingerbread kitkat and jellybean
this is the main activity code:
public class MainActivity extends Activity
implements SeekBar.OnSeekBarChangeListener,
CompoundButton.OnCheckedChangeListener,
View.OnClickListener
{
//as usual "define variables"
TextView bass_boost_label = null;
SeekBar bass_boost = null;
CheckBox enabled = null;
Button flat = null;
Button Button1;
Equalizer eq = null;
BassBoost bb = null;
int min_level = 0;
int max_level = 100;
static final int MAX_SLIDERS = 8; // Must match the XML layout
SeekBar sliders[] = new SeekBar[MAX_SLIDERS];
TextView slider_labels[] = new TextView[MAX_SLIDERS];
int num_sliders = 0;
/*=============================================================================
onCreate
=============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/*=============================================================================
onCreate
=============================================================================*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//initalize layout
setContentView(R.layout.activity_main);
//initialize the checkbox
enabled = (CheckBox)findViewById(R.id.enabled);
enabled.setOnCheckedChangeListener (this);
//initialize flat button
flat = (Button)findViewById(R.id.flat);
flat.setOnClickListener(this);
Button1 = (Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
//the seekbars
bass_boost = (SeekBar)findViewById(R.id.bass_boost);
bass_boost.setOnSeekBarChangeListener(this);
bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
sliders[0] = (SeekBar)findViewById(R.id.slider_1);
slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
sliders[1] = (SeekBar)findViewById(R.id.slider_2);
slider_labels[1] = (TextView)findViewById(R.id.slider_label_2);
sliders[2] = (SeekBar)findViewById(R.id.slider_3);
slider_labels[2] = (TextView)findViewById(R.id.slider_label_3);
sliders[3] = (SeekBar)findViewById(R.id.slider_4);
slider_labels[3] = (TextView)findViewById(R.id.slider_label_4);
sliders[4] = (SeekBar)findViewById(R.id.slider_5);
slider_labels[4] = (TextView)findViewById(R.id.slider_label_5);
sliders[5] = (SeekBar)findViewById(R.id.slider_6);
slider_labels[5] = (TextView)findViewById(R.id.slider_label_6);
sliders[6] = (SeekBar)findViewById(R.id.slider_7);
slider_labels[6] = (TextView)findViewById(R.id.slider_label_7);
sliders[7] = (SeekBar)findViewById(R.id.slider_8);
slider_labels[7] = (TextView)findViewById(R.id.slider_label_8);
//define equilizer
eq = new Equalizer (0, 0);
if (eq != null)
{
eq.setEnabled (true);
int num_bands = eq.getNumberOfBands();
num_sliders = num_bands;
short r[] = eq.getBandLevelRange();
min_level = r[0];
max_level = r[1];
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
{
int[] freq_range = eq.getBandFreqRange((short)i);
sliders[i].setOnSeekBarChangeListener(this);
slider_labels[i].setText (formatBandLabel (freq_range));
}
}
for (int i = num_sliders ; i < MAX_SLIDERS; i++)
{
sliders[i].setVisibility(View.GONE);
slider_labels[i].setVisibility(View.GONE);
}
bb = new BassBoost (0, 0);
if (bb != null)
{
}
else
{
bass_boost.setVisibility(View.GONE);
bass_boost_label.setVisibility(View.GONE);
}
updateUI();
}
/*=============================================================================
onProgressChanged
=============================================================================*/
#Override
public void onProgressChanged (SeekBar seekBar, int level,
boolean fromTouch)
{
if (seekBar == bass_boost)
{
bb.setEnabled (level > 0 ? true : false);
bb.setStrength ((short)level); // Already in the right range 0-1000
}
else if (eq != null)
{
int new_level = min_level + (max_level - min_level) * level / 100;
for (int i = 0; i < num_sliders; i++)
{
if (sliders[i] == seekBar)
{
eq.setBandLevel ((short)i, (short)new_level);
break;
}
}
}
}
/*=============================================================================
onStartTrackingTouch
=============================================================================*/
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
onStopTrackingTouch
=============================================================================*/
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
formatBandLabel
=============================================================================*/
public String formatBandLabel (int[] band)
{
return milliHzToString(band[0]) + "-" + milliHzToString(band[1]);
}
/*=============================================================================
milliHzToString
=============================================================================*/
public String milliHzToString (int milliHz)
{
if (milliHz < 1000) return "";
if (milliHz < 1000000)
return "" + (milliHz / 1000) + "Hz";
else
return "" + (milliHz / 1000000) + "kHz";
}
/*=============================================================================
updateSliders
=============================================================================*/
public void updateSliders ()
{
for (int i = 0; i < num_sliders; i++)
{
int level;
if (eq != null)
level = eq.getBandLevel ((short)i);
else
level = 0;
int pos = 100 * level / (max_level - min_level) + 50;
sliders[i].setProgress (pos);
}
}
/*=============================================================================
updateBassBoost
=============================================================================*/
public void updateBassBoost ()
{
if (bb != null)
bass_boost.setProgress (bb.getRoundedStrength());
else
bass_boost.setProgress (0);
}
/*=============================================================================
onCheckedChange
=============================================================================*/
#Override
public void onCheckedChanged (CompoundButton view, boolean isChecked)
{
if (view == (View) enabled)
{
eq.setEnabled (isChecked);
}
}
/*=============================================================================
onClick
=============================================================================*/
#Override
public void onClick (View view)
{
if (view == (View) flat)
{
setFlat();
}
if (view == (View) Button1)
{
Intent myIntent = new Intent(MainActivity.this, Guide.class);
MainActivity.this.startActivity(myIntent);
}
}
/*=============================================================================
updateUI
=============================================================================*/
public void updateUI ()
{
updateSliders();
updateBassBoost();
enabled.setChecked (eq.getEnabled());
}
/*=============================================================================
setFlat
=============================================================================*/
public void setFlat ()
{
if (eq != null)
{
for (int i = 0; i < num_sliders; i++)
{
eq.setBandLevel ((short)i, (short)0);
}
}
if (bb != null)
{
bb.setEnabled (false);
bb.setStrength ((short)0);
}
updateUI();
}
/*=============================================================================
showAbout
=============================================================================*/
public void showAbout ()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("About Simple EQ");
alertDialogBuilder.setMessage(R.string.copyright_message);
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setPositiveButton (R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog ad = alertDialogBuilder.create();
ad.show();
}
/*=============================================================================
onOptionsItemSelected
=============================================================================*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.about:
showAbout();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories