Android Main Activity is too slow - android

I have 9 buttons on my main activity which navigates to particular fragment on clicking. but it is to heavy on main thread. how can reduce the code size. can i use switch instead of defining 9 buttons
here is the main activity code
MainActivity
package com.gowarbaam.baluchistannationalparty;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutParty;
import com.gowarbaam.baluchistannationalparty.Fragments.Aims;
import com.gowarbaam.baluchistannationalparty.Fragments.CityList;
import com.gowarbaam.baluchistannationalparty.Fragments.Events;
import com.gowarbaam.baluchistannationalparty.Fragments.History;
import com.gowarbaam.baluchistannationalparty.Fragments.Martyrs;
import com.gowarbaam.baluchistannationalparty.Fragments.TwitterMain;
public class MainActivity extends AppCompatActivity {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
final Button HistoryBtn = (Button) findViewById(R.id.historyBtn);
HistoryBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new History()).commit();
}
});
final Button AimsBtn = (Button) findViewById(R.id.aimsBtn);
AimsBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Aims()).commit();
}
});
final Button MembersBtn = (Button) findViewById(R.id.membersBtn);
MembersBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new CityList()).commit();
}
});
final Button PhotoBtn = (Button) findViewById(R.id.martyrsBtn);
PhotoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Martyrs()).commit();
}
});
final Button TweetBtn = (Button) findViewById(R.id.tweetsBtn);
TweetBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TwitterMain()).commit();
}
});
final Button AboutParty = (Button) findViewById(R.id.aboutParty);
AboutParty.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutParty()).commit();
}
});
final Button b = (Button) findViewById(R.id.eventsBtn);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Events()).commit();
}
});
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutApp()).commit();
}
});
}
#Override
public void onBackPressed() {
Intent myIntent = new Intent(this, MainActivity.class);
this.startActivity(myIntent);
}
}

One reason why your application might be getting slower is the way you treat the onBackPressed() event. Every time you hit the back press button anywhere in the app you are creating a new MainActivity, but you never finish the previous one and since that's your MainActivity you are pretty much recreating your whole application on every back press.

Your problem doesn't seem to be something due to your activity class, but rather your XML files.
If anything, I would recommend creating an activity for each fragment an put them on it, just for tests. You can see how below.
AboutAppActivity
package com.gowarbaam.baluchistannationalparty;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
public class AboutAppActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerView, new AboutApp())
.commit();
}
}
And on your MainActivity
public class MainActivity extends AppCompatActivity {
// This is not for performance, just DRY
private View.OnClickListener btnOnClickListener(final Class activityClass) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), activityClass);
startActivity(i);
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(this.btnOnClickListener(AboutAppActivity.class));
}
}

Related

Move to a particular tab of bottom navigation from an activity

I am working on a project in which I used Bottom Navigation Bar. On Nav Bar, I used 4 menu items(Profile, Home, Reservation, Logout), for them I used fragment.
Moving to Home, a list of restaurant will be appear. When the user tap on any restaurant from the list, an activity( name ReservationInfo ) will be opened. There are 3 edit text fields and a button in ReservationInfo activity. When the user click on the button it will move to the fragment(Reservation) which is placed on third position of bottom nav bar.
The question is how to move from activity to fragmentand the fragment is set to the 3rd menu item of the bottom navigation bar.
Here is the code:
Resrvation.java
package restaurantlocator.application;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Resrvation extends AppCompatActivity {
Button reserve;
ImageButton imageButton;
EditText food, chooseTime, date;
DataBaseHelper db;
// ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resrvation);
db = new DataBaseHelper(this);
food = (EditText) findViewById(R.id.etfood);
chooseTime = (EditText) findViewById(R.id.ettime);
date = (EditText) findViewById(R.id.edate);
reserve = (Button) findViewById(R.id.btnreserve);
imageButton = (ImageButton) findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
}
});
//reservationInfo = new ReservationInfo();
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!emptyValidation()) {
db.AddData(new Data(food.getText().toString(),
chooseTime.getText().toString(),
date.getText().toString()));
AlertMessage();
food.setText(null);
chooseTime.setText(null);
date.setText(null);
} else {
Toast.makeText(Resrvation.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
private void AlertMessage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Resrvation.this);
builder.setTitle("Reserved!");
builder.setMessage("A notification will be send on your device regarding your reservation.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//move to fragment ReservationInfo
}
});
builder.show();
}
});
}
private boolean emptyValidation() {
if (TextUtils.isEmpty(food.getText().toString()) || TextUtils.isEmpty(chooseTime.getText().toString())) {
return true;
} else {
return false;
}
}
}
BottomNavigation.java
package restaurantlocator.application;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BottomNavigation extends AppCompatActivity {
private BottomNavigationView mMianNav;
private FrameLayout mMainFrame;
private HomeActivity homeActivity;
private ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
startService(new Intent(this, NotificationService.class));
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
homeActivity = new HomeActivity();
reservationInfo = new ReservationInfo();
setFragment(homeActivity);
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.tohome:
setFragment(homeActivity);
return true;
case R.id.toresrvation:
setFragment(reservationInfo);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
finish();
}
}
Solution:
Follow the steps below:
Step1: Add the lines as shown in below reserve click listener
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
....
Intent intent = new Intent(Resrvation.this, BottomNavigation.class);
intent.putExtra("FromReservation", "1");
startActivity(intent);
....
}
}
Next, Step2: In your write the below code in onCreate() of BottomNavigation class:
Intent i = getIntent();
String data = i.getStringExtra("FromReservation");
if (data != null && data.contentEquals("1")) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, new ReservationInfo());
fragmentTransaction.commitNow();
mMianNav.setSelectedItemId(R.id.toresrvation);
}
Try it, If any problem, do comment below.
All you need to do is just use startActivityForResults instead of startActivity when user selects a restaurant from your home fragment.
e.g :
startActivityForResult(yourIntent, 1000);
And on the reservationInfo Activity in the onClick function use
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
And then in your first activity override onActivityResult() method and set the selected fragment as reservation if request code matches
e.g:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
mMianNav.setSelectedItemId(R.id.toresrvation);
}
}

addOnBackStackChangedListener is not triggering in my android fragment

I am new to android development and I am using Fragment with the addOnBackStackChangedListener to track my back stack change but it is not listening. Here is my complete code, every button works. Just it does not capture the back stack change event
package com.practice.personal.fragdemo;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
FragmentA fa;
FragmentB fb;
FragmentManager mgr;
FragmentTransaction tx;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mgr=getFragmentManager();
txt=findViewById(R.id.message);
mgr.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
FragmentManager.BackStackEntry entry;
int c= mgr.getBackStackEntryCount();
for(int i=c-1;i>c;i--){
entry=mgr.getBackStackEntryAt(i);
Log.d("ABD",txt.getText()+entry.getName()+"\n");
txt.setText(txt.getText()+entry.getName()+"\n");
}
}
});
}
public void addA(View view){
fa = new FragmentA();
tx=mgr.beginTransaction();
tx.add(R.id.group, fa,"A");
tx.addToBackStack("A");
tx.commit();
}
public void removeA(View view){
fa = (FragmentA) mgr.findFragmentByTag("A");
if(fa!=null) {
tx = mgr.beginTransaction();
tx.remove(fa);
tx.addToBackStack("RA");
tx.commit();
}
}
public void replaceAB(View view){
fb = new FragmentB();
if(fb!=null) {
tx = mgr.beginTransaction();
tx.replace(R.id.group, fb, "B");
tx.addToBackStack("RPA");
tx.commit();
}
}
public void addB(View view){
fb = new FragmentB();
tx = mgr.beginTransaction();
tx.add(R.id.group, fb, "B");
tx.addToBackStack("B");
tx.commit();
}
public void removeB(View view){
fb = (FragmentB) mgr.findFragmentByTag("B");
if(fb!=null) {
tx = mgr.beginTransaction();
tx.remove(fb);
tx.addToBackStack("RB");
tx.commit();
}
}
public void replaceBA(View view){
fa = new FragmentA();
if(fa!=null) {
tx = mgr.beginTransaction();
tx.replace(R.id.group, fa, "A");
tx.addToBackStack("RPB");
tx.commit();
}
}
public void attachA(View view){
fa = (FragmentA) mgr.findFragmentByTag("A");
if(fa!=null) {
tx = mgr.beginTransaction();
tx.attach(fa);
tx.addToBackStack("AA");
tx.commit();
}
}
public void detachA(View view){
fa = (FragmentA) mgr.findFragmentByTag("A");
if(fa!=null) {
tx = mgr.beginTransaction();
tx.detach(fa);
tx.addToBackStack("DA");
tx.commit();
}
}
public void back(View view){
mgr.popBackStack();
}
public void pop(View view){
}
}
I am using Android Studio 3.0.1. Can somebody tell me what is wrong with it?
addOnBackStackChangedListener is used for the apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used but it does not try to switch to the framework's implementation and hence it will not be invoked.
You are using the AppCompatActivity ,so you need using the
getSupportFragmentManager() not the getFragmentManager(), see the doc: https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html

java.lang.ClassCastException: com.example.harshitbahri.expensebook.MainActivity cannot be cast to com.example.harshitbahri.expensebook.EditorActivity

I want to change the TextView of editor activity by clicking on Button buttonExpense which should also open editor activity and show value of the result in
EditText mAmountEditText.
I am getting java.lang.ClassCastException in which it is clearly written that MainActivity cannot be cast to EditorActivity
Calculator.java
package com.example.harshitbahri.expensebook;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear;
Button buttonEqual;
Button buttonExpense;
String result;
String tmp;
String operator;
TextView resultTextView;
FragmentActivity fa2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fa2 = (FragmentActivity) super.getActivity();
final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
button0 = (Button)RootView.findViewById(R.id.button0);
button1 = (Button)RootView.findViewById(R.id.button1);
......
buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);
resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("0");
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("2");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("8");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("9");
}
});
buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClearButtonClicked();
}
});
buttonSubstract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
onOperatorButtonClicked("-");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("+");
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("X");
}
});
buttonDiv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("/");
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqualButtonClicked();
}
});
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
startActivity(intent);
((EditorActivity) getActivity()).updateGoldTextView(result);
/*Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra(, result);
final int result2=1;
startActivityForResult(intent, result2);*/
}
});
return RootView;
}
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onOperatorButtonClicked(String operator) {
..
}
public void onClearButtonClicked() {
...
}
public void onNumberButtonClicked(String pos) {
..
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}`
EditorActivity.java
package com.example.harshitbahri.expensebook;
import android.app.AlertDialog;
import android.app.LoaderManager;
...
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_EXPENSE_LOADER = 0;
private Uri mCurrentExpenseUri;
private EditText mAmountEditText;
private EditText mDescEditText;
private Spinner mCategorySpinner;
private String mCategory = ExpenseEntry.CATEGORY_GENERAL;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mExpenseHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new pet or editing an existing one.
Intent intent = getIntent();
mCurrentExpenseUri = intent.getData();
// If the intent DOES NOT contain a pet content URI, then we know that we are
// creating a new pet.
if (mCurrentExpenseUri == null) {
// This is a new pet, so change the app bar to say "Add a Pet"
setTitle("Add Expense");
yet.)
invalidateOptionsMenu();
} else {
// Otherwise this is an existing pet, so change app bar to say "Edit Pet"
setTitle("Edit Expense");
getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
}
mAmountEditText = (EditText) findViewById(R.id.exp_amount);
mDescEditText = (EditText) findViewById(R.id.description);
mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
.....
}
......
finish();
}
public void updateGoldTextView(String goldAmount) {
mAmountEditText.setText(goldAmount);
}
}
MainActivity.java
package com.example.harshitbahri.expensebook;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
Calculator.OnFragmentInteractionListener ,
Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setCurrentItem(1, false);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Your fragment is loaded from MainActivity and not EditorActivity, hence the class cast exception. If you want to pre-fill some data in the editor activity, you can pass that in the intent ( the code you commented on your onclick listener) and retrieve in the EditorActivity and set your UI elements.
Edited
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}});
In your EditorActivity class, in on create
String result=getIntent().getStringExtra("result")
updateGoldTextView(result)

Android Studio quiz app saving score

I'm currently making a flag quiz app, and want to add scores. Below you can see a picture of it; each flag is a fragment, and when you press them, the right hand side allows you to submit an answer.
When you enter the right answer, a "correct" message appears, and you can go to the next flag. I want a right answer to give a score of 1, and a wrong one (or when pressed skip or hint) to give a score of zero. At the end, the score is summarized. However, I'm unsure how to do this. I've created a ScoreActivity.java file where the scores will be registered (though it's currently empty), and I've tried writing the code shown below.
Play.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.ViewGroup;
import layout.FragmentOne;
import layout.FragmentTwo;
import layout.FragmentThree;
import layout.FragmentDefault;
public class Play extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
final ImageButton imageBtn10 = (ImageButton) findViewById(R.id.imageButton10);
final ImageButton imageBtn9 = (ImageButton) findViewById(R.id.imageButton9);
final ImageButton imageBtn8 = (ImageButton) findViewById(R.id.imageButton8);
final ImageButton imageBtn7 = (ImageButton) findViewById(R.id.imageButton7);
final ImageButton imageBtn6 = (ImageButton) findViewById(R.id.imageButton6);
final ImageButton imageBtn5 = (ImageButton) findViewById(R.id.imageButton5);
final ImageButton imageBtn4 = (ImageButton) findViewById(R.id.imageButton4);
final ImageButton imageBtn3 = (ImageButton) findViewById(R.id.imageButton3);
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
FragmentDefault fd = new FragmentDefault();
fragTrans.replace(R.id.fragment_place, fd);
fragTrans.commit();
fragTrans.hide(new FragmentOne());
fragTrans.hide(new FragmentTwo());
fragTrans.hide(new FragmentThree());
imageBtn10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentOne());
fragTrans.commit();
imageBtn10.setEnabled(false);
}
});
imageBtn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentTwo());
fragTrans.commit();
}
});
imageBtn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
imageBtn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
//imageBtn4.setEnabled(false);
}
});
imageBtn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.fragment_place, new FragmentThree());
fragTrans.commit();
}
});
Button button_score = (Button)findViewById(R.id.scoreButton);
button_score.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentPlay = new Intent(Play.this, ScoreActivity.class);
startActivity(intentPlay);
}
});
}
}
FragmentOne.java (this is the fragment for the German flag)
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
//import android.widget.TextView;
public class FragmentOne extends Fragment {
EditText theAnswer;
Button ScoreButton;
private EditText userAnswer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
final TextView hintv = (TextView)v.findViewById(R.id.textHint);
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
final Button skip = (Button)v.findViewById(R.id.skipBtn);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submit.setEnabled(false);
}
});
final Button hint = (Button)v.findViewById(R.id.hintBtn);
hint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
//submit.setEnabled(false);
}
});
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (userAnswer.isChecked()){
editor.putInt("answer_value", 1);
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}
}
.isChecked() appears in red. Do I need to import something?
First of all: why are you using all of these fragment? Can't you use a single fragment updating its data to alternate between questions?
The problem is that EditText class does not have isChecked() method.
To use that method you need to use a CheckBox class.
You are using a widget to catch user input, like a text type HTML input.
Is checked is logically a property of an item that can ben checked, like an HTML checkbox
You are putting a text into your EditText (user answer) and then you are asking to a string container field if it's checked. It does not make sense.
What you really needs is store if user answer match right answer (like in a boolean). You can set this value when you set "correct" in result TextView, someting like this:
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
// keep trace of user answer result
wellAnswered = true;
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
Then you can update your FragmentOne code as follows:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (wellAnswered){
editor.putInt("answer_value", 1);
// remember to reset your variable for next question
wellAnswered = false;
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}
To save the Scores , you can use SharedPreferences. As per the docs:
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
How do I use SharedPreferences to store my Score?
Every time the user clicks the submit button, inside the onClickListener() retrieve the existing value from the SharedPreferences file and increment it by one.
So, How do I do it?
Well First, create an instance of SharedPreferences:
private SharedPreferences sharedpreferences;
then initialize it:
sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
then inside the onClickListener() :
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("SCORE", sharedpreferences.getInt("SCORE",0)+1);
editor.apply();
So what this does is , it creates a Key value pair, where the key is SCORE, and putInt() method inserts a value associated with the key, in this case SCORE.
NOTE : sharedpreferences.getInt("SCORE",0)+1) what this does is it increments, the score by one. And finally apply() saves the data to the SharedPreferences file.
How do I retrieve the Score ?
sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
int score = sharedpreferences.getInt("SCORE",0)
Where, the 0 is the default value.
Hope it helps!
So I have amended the code in FragmentOne.java, and now it looks like this:
public class FragmentOne extends Fragment {
private EditText userAnswer;
private boolean wellAnswered;
private Button ScoreButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, null);
userAnswer = (EditText)v.findViewById(R.id.editText);
final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
final TextView hintv = (TextView)v.findViewById(R.id.textHint);
final Button submit = (Button)v.findViewById(R.id.submitBtn1);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String theAnswer = (userAnswer.getText().toString());
if (theAnswer.equalsIgnoreCase("Germany")) {
//TextView tv = (TextView)v.findViewById(R.id.showCorrect);
tv.setText("Correct!");
wellAnswered = true;
} else {
}
submit.setEnabled(false);
// updateScore();
}
});
final Button skip = (Button)v.findViewById(R.id.skipBtn);
skip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submit.setEnabled(false);
}
});
final Button hint = (Button)v.findViewById(R.id.hintBtn);
hint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
//submit.setEnabled(false);
}
});
return v;}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ScoreButton = (Button)getView().findViewById(R.id.scoreButton);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
ScoreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
if (wellAnswered){
editor.putInt("answer_value", 1);
// remember to reset your variable for next question
wellAnswered = false;
}
else {
editor.putInt("answer_value", 0);
}
editor.commit();
}
});
}
}
I have used the suggestions from your answers and I get no errors, however, the app crashes when I press the flags. Any idea what I'm doing wrong?
STACKTRACE:
01-06 20:08:18.152 3912-3912/? I/art: Not late-enabling -Xcheck:jni (already on)
01-06 20:08:18.153 3912-3912/? W/art: Unexpected CPU variant for X86 using defaults: x86
01-06 20:08:18.189 3912-3919/? I/art: Debugger is no longer active
01-06 20:08:18.189 3912-3919/? I/art: Starting a blocking GC Instrumentation
01-06 20:08:18.294 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.299 3912-3912/? I/InstantRun: Instant Run Runtime started. Android package is com.example.karolinawullum.quizapp, real application class is null.
[ 01-06 20:08:18.311 1560: 1583 D/ ]
HostConnection::get() New Host Connection established 0x8d661580, tid 1583
01-06 20:08:18.378 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.487 3912-3912/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
01-06 20:08:18.608 3912-3933/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-06 20:08:18.610 3912-3933/? D/OpenGLRenderer: Swap behavior 1
01-06 20:08:18.637 3912-3933/? E/EGL_emulation: tid 3933: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
01-06 20:08:18.637 3912-3933/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x90557900, error=EGL_BAD_MATCH

How to change webview orientation in android while coming back from another screen

I am having a screen which has a WebView showing a UI developed in HTML and PHP. Now, when i migrate to a different screen in Android and want to come back to my parent screen, I want to have a NEW WebView layout. Even though I am passing a String variable back for validating purposes, but still then it does not work out. Does this have to do anything with the savedInstanceState? Any suggestions would be appreciated. Below is the code snippet.
package com.example.notifboard;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class AdminLogin extends Activity {
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flag = true;
}
protected void onResume() {
super.onResume();
if (flag == true) {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
finish();
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
finish();
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/AdminLogin.php");
}
else {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/NewEvents.php");
}
}
}

Categories

Resources