screen blinks during activity starts in android - android

I have redirecting the fragment to activity.Progress wheel rotate before getting the data and then it will stops after getting data from web service.After loading the data from web service the screen gets blinks fraction of seconds.After blinking all the data are displayed in activity.How to remove the blinking effects in android?
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "arial.ttf");
fontChanger.replaceFonts((ViewGroup) this.findViewById(android.R.id.content));
SharedPreferences prefs1 = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
userID= prefs1.getString("userid", null);
System.out.println("userid" + userID);
Intent i = getIntent();
useridpost = i.getStringExtra("postuserid");
subuser=i.getStringExtra("subuserid");
btnBack=(ImageButton)findViewById(R.id.button_back);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checking){
Intent cancel = new Intent(PostActivity.this, MainActivity.class);
cancel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
cancel.putExtra("testedit", "testedit");
startActivity(cancel);
}
else{
finish();
}
}
});
emptyView=(TextView)findViewById(R.id.empty_view);
if(subuser!=null){
if(subuser.equals(userID)){
emptyView.setText("No Posts for you");
}
else{
emptyView.setText("No Posts to show");
}
}
if(useridpost==null) {
// editor.putString("useridfromprofile", userID);
userID = prefs1.getString("userid", null);
System.out.println("user id from shared preferences"+userID);
}
else
{
userID=useridpost;
System.out.println("user id from arguments"+userID);
}
pw=(ProgressWheel) findViewById(R.id.pw_spinner);
obj.styleRandom(pw,getApplicationContext());
recyclerView=(ListView)findViewById(R.id.recycler_view);
// recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter=new CustomPostAdapter1(this,feedsList,PostActivity.this);
recyclerView.setAdapter(adapter);
getProfilePosts();
}

try this
On the exiting activity, call getWindow().setExitTransition(null);
On the entering activity, call getWindow().setEnterTransition(null);
It will prevent the fade out of the exiting activity and the fade in of the entering activity, which removes the apparent blinking effect.

Related

Showing results for a quiz app (Android Studio)

I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}

how to pop up a dialog box for the first time when i launched my app for the first time?

i want to pop up a dialog box when my app is open for the first time in a device.i want to show in popup box that how to use the app.
if the app is opening for the first time it will show the dialog box ,otherwise it will simply avoid to show the dialog box.and the activities also will change according to the first use or normal use.for first time use it will show a activity1 or else it will show activity2.please help me.
this is my activity which show a image when app is opened
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_name);
new Timer().schedule(new TimerTask() {
public void run() {
// here i want to go to another activity acording to the first time use or normal time
}
}, 3000);
}
public class class_name extends AppCompatActivity {
public static final String MyPREFERENCES2 = "MyPrefs" ;
SharedPreferences sharedpreferences2;
public boolean isFirstRun;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_name);
new Timer().schedule(new TimerTask() {
public void run() {
checkFirstRun();
}
}, 3000);
}
public void checkFirstRun() {
System.out.println("its in check first run");
isFirstRun = getSharedPreferences("PREFERENCE2", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun){
startActivity(new Intent(class_name.this, new_activity1.class));
getSharedPreferences("PREFERENCE2", MODE_PRIVATE)
.edit()
.putBoolean("isFirstRun", false)
.commit();
}
else{
startActivity(new Intent(class_name.this, new_activity2.class));
}
}
}
final String FIRST_TIME_KEY = "com.example.app.MainActivity.firstTimeKey";
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstTime = sp.getBoolean(FIRST_TIME_KEY, false);
if(isFirstTime) {
SharedPreferences.Editor edit = sp.edit();
edit.putBoolean(FIRST_TIME_KEY, true);
edit.apply();
//show the dialog
}

Add items to listview from other activity

scenario:
First mainactivity launches and from the menu option user launches second activity using intent and there he adds some text to edittext and get that edittext value using intent to the first activity and add that value to the listview.
FirstActivity:
public class MainActivity extends Activity {
ListView lv;
EditText et;
String AddedTask ;
ArrayList<Model> modelList;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
if (intent.hasExtra("NewTask")) {
AddedTask = this.getIntent().getExtras().getString("NewTask");
lv = (ListView) findViewById(R.id.listViewData);
String name = AddedTask;
Model md = new Model(name);
modelList.add(md);
adapter = new CustomAdapter(getApplicationContext(), modelList);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_add_task:
Intent i = new Intent(MainActivity.this, AddTask.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Second Activity:
public class AddTask extends Activity {
Button addtask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
// get action bar
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
addtask = (Button) findViewById(R.id.btnaddlist);
findViewById(R.id.btnaddlist).setOnClickListener(
new View.OnClickListener() {
public void onClick(View arg0) {
EditText edit = (EditText) findViewById(R.id.tskname);
Intent i = new Intent(AddTask.this,
MainActivity.class);
//Bundle bundle = new Bundle();
String TaskName = edit.getText().toString();
//bundle.putString("NewTask", TaskName);
i.putExtra("NewTask", TaskName);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//i.putExtras(bundle);
startActivity(i);
}
});
}
}
Now my problem is I'm able to add the data to the listview but each time I come back to mainactivity the previous data which was added is lost and updating the old data with my new data.
I have searched for many SO answers and most of them suggest to add adapter.notifyDataSetChanged(); which I have already tried and nothing worked.
I have done by checking the adapter is null or updating the data this way and getting null pointer exception:
if ( adapter== null )
{
adapter = new CustomAdapter(getApplicationContext(), modelList);
lv.setAdapter(adapter);
}
Can anyone say me how do I get this working ?
new View.OnClickListener() {
public void onClick(View arg0) {
EditText edit = (EditText) findViewById(R.id.tskname);
Intent i = new Intent(AddTask.this,
MainActivity.class);
//Bundle bundle = new Bundle();
String TaskName = edit.getText().toString();
//bundle.putString("NewTask", TaskName);
i.putExtra("NewTask", TaskName);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//i.putExtras(bundle);
startActivity(i);
}
});
You are starting a new Activity each time you want to add an item.
Consider using
startActivityForResult()
Link to Android Documentation
Even if startActivityForResult() is IMHO the best way to fix your problem, i'll give you a hint why it doesn't show your "old" data.
You don't finish your first Activity when going to the Second. You could aswell just finish your second activity and your MainActivity would run into
onResume()
therefor check the Android lifecycle
Don't use putextra and intent techniques. Follow below technique.
In main activity create sharedpref as follows:
public static final String SharedPref = "MyPreferences";
In activity 2 insert this code.
SharedPreferences settings=null;//declaration
settings=getSharedPreferences(SharedPref,0);//initialization
String TaskName= edit.getText().toString();
SharedPreferences.Editor editor = settings.edit();
editor.putString("NewTask", TaskName);
editor.commit();
finishfromchild(AddTask.this);
In main activity:
SharedPreferences settings=null;//declaration
In onCreate
//now initialise settings
settings=getSharedPreferences(SharedPref,0);//SharedPref is the foldername
//of your sharedpreferences(you create it first)
//Now create onResume method
public void onResume()
{
super.onResume();
AddedTask=settings.getString("NewTask", "");
lv = (ListView) findViewById(R.id.listViewData);
String name = AddedTask;
Model md = new Model(name);
modelList.add(md);
adapter = new CustomAdapter(getApplicationContext(), modelList);
lv.setAdapter(adapter);
}
Hope this works. I did the same in my previous project.

realm-java data lost when restarting application

I'm using realm-android 0.74.0 with android 4.4.2
I create an instance of realm, populate it with objects and commit the transaction.
My objects are saved fine. I can load them and manipulate them.
But each time i restart my application the data is lost
Has anyone run into the same problem ?
Christian from Realm here.
Your login button onClick handler have this method:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
...
// Delete database
Realm.deleteRealmFile(getActivity());
...
}
});
This deletes the default realm file and by that your data. Where you trying to accomplish something else by this line?
I was doing the following
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
final Button button = (Button) rootView.findViewById(R.id.connect);
final EditText username = (EditText) rootView.findViewById(R.id.username);
final EditText password = (EditText) rootView.findViewById(R.id.password);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Hide keyboard
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
// Call user login service
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(getString(R.string.app_url_base))
.build();
AppService service = restAdapter.create(AppService.class);
service.login(username.getText().toString(), password.getText().toString(), new Callback<User>() {
#Override
public void success(User user, Response response) {
if (user.isSuccess()) {
SharedPreferences prefs = getActivity().getSharedPreferences(Const.PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Log.d(TAG, "Logged username: " + user.getUsername());
editor.putString(getString(R.string.pref_username), user.getUsername());
editor.putString(getString(R.string.pref_password), user.getPassword());
editor.putString(getString(R.string.pref_lastname), user.getLastname());
editor.putString(getString(R.string.pref_firstname), user.getFirstname());
editor.putString(getString(R.string.pref_md5), user.getMd5());
editor.commit();
Toast.makeText(getActivity(), getString(R.string.success_login), Toast.LENGTH_SHORT).show();
// Delete database
Realm.deleteRealmFile(getActivity());
// Delete log file
File logFile = new File(Const.LOG_FILE);
if (logFile.exists()) logFile.delete();
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.container, TasksFragment.newInstance(2, 0))
.commit();
//((MainActivity) getActivity()).openDrawer();
} else {
Toast.makeText(getActivity(), getString(R.string.error_login), Toast.LENGTH_SHORT).show();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.d(TAG, "retrofitError:" + retrofitError.getMessage());
Toast.makeText(getActivity(), getString(R.string.error_login), Toast.LENGTH_SHORT).show();
}
});
}
});
return rootView;
}
but by moving
Realm.deleteRealmFile(getActivity());
before the retrofit call it's seems to work ok
The TasksFragment is running a Service which persist the RealmObjects
Thanks for your help

User setup activity of android app

I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()

Categories

Resources