Second activity does not load in login form - android-activity

I created a simple app of login form but it did not go to second activity after login. There is no error in the code. Will you please help me, here is the code:
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Info;
private Button Login;
private int counter=5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText)findViewById(R.id.editText);
Password = (EditText) findViewById(R.id.editText2);
Info = (TextView)findViewById(R.id.textView);
Login = (Button) findViewById(R.id.btn);
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(Name.getText().toString(), Password.getText().toString());
}
});
}
private void validate(String userName, String userPasswor) {
if ((userName == "admin") && (userPasswor == "1234")) {
Intent intent= new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
} else {
counter--;
Info.setText("No of Attempts Remaining: " + String.valueOf(counter));
if (counter == 0) {
Login.setEnabled(false);
}
}
}
}

You write your code
if((userName =="admin") && (userPasswor=="1234"))
{
Intent intent= new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
change this code as
if((userName.equals("admin")) && (userPasswor.equals("1234")))
{
Intent intent= new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
also enter Second activity in Android.mainfeast file.

Related

Getting skipped frames with RxAndroid on a simple call

I'm implementing in a LauncherActivity (with just a loading indicator) an Observable (Single) from RxJava library to login with the previously recorded users credentials.
The activity is very very simple, and yet I get a skipped frames warning (40ish), both on my phone and on emulator, and I can't figure out why (though sometimes it doesn't show up).
Here is the code :
public class LauncherActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
if (UsersUtils.hasCredentialsRecorded(this)) {
getAccessToken();
} else {
login();
}
}
public void getAccessToken() {
Callable<Token> callable = new Callable<Token>() {
#Override
public Token call() throws Exception {
final Map<String, byte[]> credentials = UsersUtils.getCredentials(getApplicationContext());
Token token = OauthCalls.getToken(new String(credentials.get(UsersUtils.PREFERENCES_USER_KEY)),
new String(credentials.get(UsersUtils.PREFERENCES_PASS_KEY)));
return token;
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.subscribe(new DisposableSingleObserver<Token>() {
#Override
public void onSuccess(Token token) {
if (token == null) {
login();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onError(Throwable e) {
login();
}
});
}
public void login() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Thanks a lot for your help !

Android Webview signout issue

In my webview app when I run the app for the first time and log out from a user session, close the app and then when I open the app again instead of asking user credentials I find myself already logged in. I tried clearing cookies but then it always require sign in on every restart. I only want it to ask for sign in when the user logs out from the app.
Please Help!!
Here is a snippet of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.framelayout);
bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setMax(100);
webview = (WebView) findViewById(R.id.mywebview);
webview.clearCache(true);
webview.clearHistory();
WebSettings mWebSettings = webview.getSettings();
mWebSettings.setSaveFormData(false);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webview = (WebView) findViewById(R.id.mywebview);
webview.setWebViewClient(new HelpClient());
webview.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(newProgress);
setTitle("Loading....");
if (newProgress == 100){
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, newProgress);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.setVerticalScrollBarEnabled(false);
webview.loadUrl(WebAddress);
webview.loadUrl("javascript:window.location.reload(true)");
swipe.setRefreshing(false);
bar.setProgress(0);
}
private class HelpClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
try {
webview.stopLoading();
} catch (Exception e) {
}
if (webview.canGoBack()) {
webview.goBack();
}
webview.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(view, request, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (webview.canGoBack()){
webview.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Run below code before loadUrl()
WebStorage webStorage = WebStorage.getInstance();
webStorage.deleteAllData();
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
I test it using Gmail account
CookieSynManager is now deprecated. This works for me :
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)

android code for switching between activities

In an activity there are 2 buttons. 1st button should open one activity and the 2nd button should open another activity. The following code is what I wrote. Please help me.
Button voice;
Button msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
msg=(Button)findViewById(R.id.text);
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.voice)
{
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_voice_msg);
}
else if(view.getId()==R.id.text)
{
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_text_msg);
}
}
Replace this;
`Button voice;
Button msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
voice.setOnClickListener(this);
msg=(Button)findViewById(R.id.text);
msg.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.voice)
{
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_voice_msg);
}
else if(view.getId()==R.id.text)
{
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_text_msg);
}
}`
By this:
Button voice;
Button msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
msg=(Button)findViewById(R.id.text);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.voice:
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
break;
case R.id.text:
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
break;
default:
break;
}
}
Also implements OnClickListener in your class
please try below code:
button1 = (Button)findViewById(R.id.Button1);
button1.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
intent = new Intent(CurrentActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
});
button2 = (Button)findViewById(R.id.Button2);
button2.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
intent = new Intent(CurrentActivity.this, ThirdActivity.class);
startActivity(intent);
finish();
}
});

edit spinner in one activity from another activity

i created Activity5 for manage values on other activities...
in Activity3 i have a spinner...
Spinner spinner1;
ArrayList<String> SAlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
ArrayList<String> SAList = intent.getStringArrayListExtra("StringArrayList");
spinner1=(Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,SAList);
spinner1.setAdapter(adp);
}
i think if i build new spinner (for showing it to user) in activity5 and edit it , then passing array list of this spinner to activity3, this is possible...
Activity5:
Spinner sp;
EditText et;
ArrayList<String> li;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity5);
getActionBar().setDisplayHomeAsUpEnabled(true);
li=new ArrayList<String>();
li.add("first item");
sp=(Spinner) findViewById(R.id.spinner1);
Button butt=(Button) findViewById(R.id.button1);
Button butt1=(Button) findViewById(R.id.button2);
et=(EditText)findViewById(R.id.editText1);
add();
butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
li.add(et.getText().toString());
et.setText(null);
add();
}
});
butt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity5.this, MainActivity3.class);
intent.putStringArrayListExtra("StringArrayList", li);
startActivity(intent);
}
});
}
private void add() {
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,li);
sp.setAdapter(adp);
}
but when i launch app and open activity3 it shows "unfortunately app has stopped" !!!
help me plz!
when you open activity3 from main menu, on that event your getting SAList null,
try doing this,when SAList is null it will show empty spinner.
Intent intent = getIntent();
if(intent.getStringArrayListExtra("StringArrayList")!=null)
{
ArrayList<String> SAList = intent.getStringArrayListExtra("StringArrayList");
}else
{
ArrayList<String> SAList=new ArrayList<String>();
}

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}