Buttons for opening a new activity? - java

So, I have three activities/screens. On the first screen, there's a button, that when pressed, opens the second screen. On the second screen, there's a button to open screen 3, but also another button to go back to screen 1. I can't get both buttons on screen 2 to work. (Either one works and the other doesn't and vice versa).
Screen 1 Java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FirstActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.part1to2);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Screen2.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Screen 2.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen2 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button next = (Button) findViewById(R.id.goto1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
Button next = (Button) findViewById(R.id.goto3);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Screen3.class);
startActivityForResult(myIntent, 0);
finish();
}
});
}
});
}
}
Screen 3.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen3 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
}
}
And my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gamer.network2"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".FirstActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Screen2"></activity>
<activity android:name=".Screen3"></activity>
</application>
</manifest>
So, how do I get both buttons on Screen 2 to work at the same time?

Both buttons are the same name and are declared wrongly.
Button next = (Button) findViewById(R.id.goto1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
Button next = (Button) findViewById(R.id.goto3);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Screen3.class);
startActivityForResult(myIntent, 0);
finish();
}
});
}
});
Try instead:
Button goto3 = (Button) findViewById(R.id.goto3);
goto3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Code here
}
});
Button goto1 = (Button) findViewById(R.id.goto1);
goto1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Code here
}
});
Edit: Cole, see below, this is code working from an app of mine, with two different buttons pointing to two different activities. I have also included the code from the AndroidManifest.xml.
mBtnPlayCourse = (Button) findViewById(R.id.btn_screenstart_playcourse);
mBtnNewCourse = (Button) findViewById(R.id.btn_screenstart_newcourse);
mBtnPlayCourse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Screen_Start.this, Screen_Players.class);
startActivity(i);
}
});
mBtnNewCourse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Screen_Start.this, Screen_CreateCourse.class);
startActivity(i);
}
});
In the AndroidManifest.xml:
<activity android:name=".Screen_CreateCourse" android:label="#string/app_name">
</activity>
<activity android:name=".Screen_Players" android:label="#string/app_name">
</activity>

Related

Button click not switching activity

I've been trying to get this app to switch activities by simply clicking the button, but the app simply refreshes and I stay on the same activity. Nothing happens. And if I uncomment the lines of code for my second activity, the OnClick ones, I get null pointer errors. I have no idea what I could be doing wrong. Here's my code in main activity:
package com.example.commontaskslite;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.Button;
import android.widget.CompoundButton;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TimePicker alarmClock;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private Button search;
private Button redial;
private Button address;
boolean checked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmClock = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
search = (Button) findViewById(R.id.search);
redial = (Button) findViewById(R.id.redial);
address = (Button) findViewById(R.id.address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openSearch(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(isChecked){
checked = true;
onToggleClicked();
}
else{
checked = false;
onToggleClicked();
}
}
});
}
public void openSearch(View V){
Intent _intent = new Intent(MainActivity.this,Search.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(MainActivity.this,Redial.class);
startActivity(_intent);
}
public void openShowAddress(View V){
Intent _intent = new Intent(MainActivity.this,ShowAddress.class);
startActivity(_intent);
}
public void onToggleClicked(){
long time;
if(checked) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmClock.getHour());
calendar.set(Calendar.MINUTE, alarmClock.getMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0) {
time = time + (1000 * 60 * 60 * 12);
} else {
time = time + (1000 * 60 * 60 * 24);
}
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this,"ALARM OFF", Toast.LENGTH_SHORT).show();
AlarmReceiver.ringtone.stop();
}
}
}
Here's the code in the second activity:
package com.example.commontaskslite;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class Search extends AppCompatActivity {
private PendingIntent pendingIntent;
private Button alarm;
private Button redial;
private Button address;
private SearchView searchView;
private String searchQuery;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = getIntent();/*
address = (Button) findViewById(R.id.address2);
redial = (Button) findViewById(R.id.redial2);
alarm = (Button) findViewById(R.id.alarm);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
searchQuery = s;
return true;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
alarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity(view);
}
});*/
}
public void openShowAddress(View V){
Intent _intent = new Intent(this,ShowAddress.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(this,Redial.class);
startActivity(_intent);
}
public void openMainActivity(View V){
Intent _intent = new Intent(this,MainActivity.class);
startActivity(_intent);
}
}
And here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.commontaskslite">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.CommonTasksLite">
<activity
android:name=".ShowAddress"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ALL_APPS"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Redial"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Search"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver">
</receiver>
</application>
</manifest>
summarizing the answer that was found in comments.
Change setContentView(R.layout.activity_main); to another layout other than activity_main in Search Activity.

Application different error depending on device

Logcart is giving error like, on my phone
2020-05-03 17:48:38.715 1785-2071/com.example.tasteportal04b E/libGLESv2: ASUS:glGetString HOOK !!!! name=0x1f01,ret=Adreno (TM) 512
On some devices like Samsung S6, the app is not starting, displaying a crash message, on my Asus works perfectly
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tasteportal04b">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_taste" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".nootificare"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
android:largeHeap="true"
>
<activity android:name=".MainActivity"
android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" android:screenOrientation="portrait"
android:theme="#style/SplashTheme"></activity>
</application>
</manifest>
NewActivity.java
package com.example.tasteportal04b;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.Objects;
public class NewActivity extends AppCompatActivity {
Toolbar toolbar;
private WebView webView;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("TASTE Live");
toolbar.setSubtitle("v1.0");
toolbar.setLogo(R.mipmap.tasteico);
toolbar.setTitleTextColor(getResources().getColor(R.color.colortitle));
toolbar.setSubtitleTextColor(getResources().getColor(R.color.colorsubtitle));
webView = findViewById(R.id.webView);
progressbar = findViewById(R.id.progressbar);
progressbar.setMax(100);
webView.loadUrl("https://");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
}
});
FloatingActionButton facebook = findViewById(R.id.Facebook);
FloatingActionButton classroom = findViewById(R.id.Classroom);
FloatingActionButton blog = findViewById(R.id.Blog);
FloatingActionButton youtube = findViewById(R.id.Youtube);
FloatingActionButton drive = findViewById(R.id.Drive);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
Intent gofb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/"));
startActivity(gofb);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/TASTEATB")));
}
showToast("T.A.S.T.E Facebook");
}
});
classroom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goclass = new Intent(Intent.ACTION_VIEW, Uri.parse("https://classroom.google.com/u/0/c/NzgzMTc2MDk5NjNa"));
startActivity(goclass);
showToast("T.A.S.T.E Classroom");
}
});
blog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goblog = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(goblog);
showToast("T.A.S.T.E Blog");
}
});
youtube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goyt = new Intent(Intent.ACTION_VIEW);
try {
goyt.setData(Uri.parse("https://"));
goyt.setPackage("com.google.android.youtube");
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/channel/")));
}
startActivity(goyt);
showToast("T.A.S.T.E Youtube");
}
});
drive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent godrive = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(godrive);
showToast("T.A.S.T.E Drive");
}
});
}//inchide oncreate
public void showToast(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.bug:
Intent gobug = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(gobug);
showToast("Raporteaza un bug");
break;
case R.id.update:
showToast("Update aplicatie");
webView.loadUrl("https://");
break;
}
return super.onOptionsItemSelected(item);
}
}

For some reason data is not sent from 3rd Activity to main Activity and the app crashes while the 2nd Activity works perfectly fine

package com.example.intent;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText etEnterName;
Button btnActivity2;
Button btnActivity3;
TextView tvMessage;
final int ACTIVITY3=3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etEnterName=findViewById(R.id.etEnterName);
btnActivity2=findViewById(R.id.btnActivity2);
btnActivity3=findViewById(R.id.btnActivity3);
btnActivity2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etEnterName.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "please enter all fields", Toast.LENGTH_SHORT).show();
}
else {
String name = etEnterName.getText().toString().trim();
Intent intent = new Intent(MainActivity.this,
com.example.intent.Activity2.class);
intent.putExtra("name",name);
startActivity(intent);
}
}
});
btnActivity3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
com.example.intent.Activity3.class);
startActivityForResult(intent,ACTIVITY3);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==ACTIVITY3)
{
if (resultCode==RESULT_OK){
tvMessage.setText(data.getStringExtra("surname"));
}
if(resultCode==RESULT_CANCELED){
tvMessage.setText("no data received");
}
}
}
}
3rd Activity
package com.example.intent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity3 extends AppCompatActivity {
Button btnSubmit;
EditText etSurname;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
btnSubmit=findViewById(R.id.btnSubmit);
etSurname=findViewById(R.id.etSurname);
btnCancel=findViewById(R.id.btnCancel);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(etSurname.getText().toString().isEmpty()){
Toast.makeText(Activity3.this,"please enter your surname" Toast.LENGTH_SHORT).show();
}
else {
String surname = etSurname.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("surname",surname);
setResult(RESULT_OK,intent);
Activity3.this.finish();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
Activity3.this.finish();
}
});
}
}
This is the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intent">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activity3"></activity>
<activity android:name=".Activity2" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Explanation
Blockquote
I following a youtube video and i cant find where i am getting the whole thing wrong. The button main activity works perfectly fine and take me to the third intent but when i enter data in edit text box and click the submit button the app crashes.
I had not added this line of code.
tvMessage = findviewbyid (R.id.tvMessage);
My bad –

can we make two launcher activities and launch one based on some condition?

my launcher activity is loginActivity and i want that when the user selects a college and opens the app for the second time he should be moved to another activity TestYip (and not login activity). that is the launcher activty should change once the user has logged in. for this i made a fuction getCollege in Select_Collage activity which is called from the loginActivity .
but its not working.. the code is given :
Select_Collage
package notes.test.firebase;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class Select_Collage extends AppCompatActivity {
// List view
public ListView lv;
public TextView tv;
public String str;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage);
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
// Listview Data
/* final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
*/
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.college_selection_text_view, R.id.product_name, products);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3){
tv = (TextView) arg1.findViewById(R.id.product_name);
str = tv.getText().toString().trim();
if (str.equals(products[0]))
{
Intent int0 = new Intent(Select_Collage.this, TestYip.class);
startActivity(int0);
}
else if(str.equals(products[1])) {
Intent int1 = new Intent(Select_Collage.this, MainListDisplay.class);
startActivity(int1);
}
}
});
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Select_Collage.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public void getCollege () {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
if (str.equals(products[0]))
{
editor.putInt("key", 1);
editor.apply();
//Intent int0 = new Intent(getAppl,TestYip.class);
//Intent int0 = new Intent(getApplicationContext(),TestYip.class);
//startActivity(int0);
} else {
editor.putInt("key", 0);
editor.apply();
}
}
}
LoginActivity
package notes.test.firebase;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null ) {
Select_Collage s = new Select_Collage();
//s.getCollege();
//startActivity(new Intent(LoginActivity.this, MainActivity.class));
s.getCollege();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int i = preferences.getInt("key",0);
///startActivity(new Intent(LoginActivity.this, MainActivity.class));
if (i==1)
{
startActivity(new Intent(LoginActivity.this, TestYip.class));
}
else
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
// set the view now
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="notes.test.firebase">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_profile"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".SignupActivity"
android:label="#string/title_activity_login"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ResetPasswordActivity"
android:label="#string/title_activity_reset_password"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".TestYip"
android:label="#string/title_test"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Computer_Notes" />
<activity
android:name=".MainListDisplay"
android:label="#string/Select_Subject"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<activity
android:name=".Select_Collage"
android:label="#string/Select_Collage"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
<activity android:name=".SearchResulltsActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
please tell how i can move from one activity to another based on a condition.
Dont use LoginActivity as your launcher activity. In your LoginActivity, save some flag value to SharedPreferences to indicate the user has logged in, and then in the onCreate of your other Activity(Set this one to launcher), check for this value, if its not present, then go to LoginActivity.
I will recommend the best way around. Whenever you are stuck on such things, Splash screen will help you.
Let me explain how:-
Just make splash screen as Launcher activity. If you don't want that to display it for much longer, just have the handler run for 1-2 seconds. Now look at the code below.
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
//SharedPreference to Store API Result
SharedPreferences pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
SharedPreferences.Editor editor = pref.edit();
editor.apply();
email = pref.getString("login", null);
int SPLASH_TIME_OUT = 3000;
if (email != null) {
//It means User is already Logged in so I will take the user to Select_College Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Select_College.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
} else {
//It means User is not Logged in so I will take the user to Login Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Login.class);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
}
Login.java
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_login);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
Login();
}
private void login() {
//If login is successfull, before moving to next activity, store something in sharedpreference with name login. It can be email or just a string as "true"
SharedPreferences.Editor editor = pref.edit();
editor.putString("login", email);
editor.apply();
Intent intent = new Intent(DoctorLogin.this, Select_Collage.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}
Select_Collage.java
public class Select_Collage extends AppCompatActivity {
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_message);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
//Somewhere on Signout button click, delete the login sharedpreference
signOut();
}
private void signOut() {
SharedPreferences.Editor editor = pref.edit();
editor.remove("login");
editor.apply();
Intent intent = new Intent(Select_Collage.this, Login.class);
startActivity(intent);
finish();
}
}
So that's how you can solve this problem. Keep Coding :)
Try saving a boolean or int in shared preference.
Set the int or boolean in Select_collage
Get its value in LoginAcitivity , and check condition the way you did it.
I guess the problem with your code is when you check condition in LoginAcitivity , the value in Select_collage activity is not set as it is not created.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
You have to start a splashcreen activity.. in that activity u need to check the condition (oncreate function)
for which activity should be launch to the next..

How do I call my NoteMain class when I click on the "Notes" Button in my android app

As above. I'm to sure what I'm doing wrong. Here is the code for the MainActivity.java and the code for the NoteMain.java When I click on the Notes button on the home screen when the app loads it says Unfortunately,(app name) has stopped.
I don't know why? Any help is appreciated.
Thanks in advance
MainActivity:
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button buttonConverter;
Button buttonCalculator;
Button buttonNotePad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ConvertBtn = (Button) findViewById(R.id.butonConverter);
ConvertBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CentInch.class);
startActivity(intent);
}
});
Button CalcBtn = (Button) findViewById(R.id.buttonCalc);
CalcBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Calculator.class);
startActivity(intent);
}
});
Button NoteBtn = (Button) findViewById(R.id.buttonNotes);
NoteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,NoteMain.class);
startActivity(intent);
}
});
}
public void setupConverterButton(){
buttonConverter = (Button) findViewById(R.id.butonConverter);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void CentToInch(){
buttonConverter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class centClass = Class
.forName("com.qub.buildersbuddy.CentInch");
Intent myintent = new Intent(MainActivity.this,centClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupCalculatorButton(){
buttonCalculator = (Button) findViewById(R.id.buttonCalc);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Calculator(){
buttonCalculator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class calcClass = Class
.forName("com.qub.buildersbuddy.Calculator");
Intent myintent = new Intent(MainActivity.this,calcClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupNotesButton(){
buttonNotePad = (Button) findViewById(R.id.buttonNotes);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Notes(){
buttonNotePad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class NoteMain = Class
.forName("com.qub.buildersbuddy.NoteMain");
Intent myintent = new Intent(MainActivity.this,NoteMain);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
}
NoteMain
package com.qub.buildersbuddy;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class NoteMain extends Activity implements OnItemClickListener, OnClickListener {
private SharedPreferences spNotes;
private ArrayList<Note> notes;
private Button addNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_main);
this.addNote = (Button) findViewById(R.id.addNoteButton);
this.addNote.setOnClickListener(this);
spNotes = getSharedPreferences("notes", Context.MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
showNotes();
ListView list = (ListView) findViewById(R.id.listNotes);
CustomAdapter aa = new CustomAdapter(this, getLayoutInflater(), this.notes, spNotes);
list.setAdapter(aa);
list.setOnItemClickListener(this);
}
private void showNotes() {
this.notes = new ArrayList<Note>();
Map map = spNotes.getAll();
for (Object o : map.entrySet()) {
Entry e = (Entry<String, String>) o;
this.notes.add(new Note((String)e.getKey(), (String)e.getValue()));
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Intent intent = new Intent(this, NoteActivity.class);
intent.putExtra("title", this.notes.get(position).getTitle());
intent.putExtra("text", this.notes.get(position).getText());
startActivity(intent);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, NoteActivity.class);
startActivity(intent);
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qub.buildersbuddy"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.qub.buildersbuddy.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.qub.buildersbuddy.CentInch"
android:label="#string/title_activity_cent_inch" >
</activity>
<activity
android:name="com.qub.buildersbuddy.Calculator"
android:label="#string/title_activity_calculator" >
</activity>
<activity
android:name="com.qub.buildersbuddy.NotePad"
android:label="#string/title_activity_note" >
</activity>
</application>
</manifest>
Its probably because you don't have the NoteMain activity defined in your Manifest.
<activity
android:name="com.qub.buildersbuddy.NoteMain"
android:label="#string/title_activity_note" >
</activity>

Categories