setOnClickListener not working as expected - android

First of all, I'm a newbie to android.
I have three activities in my Application. i.e, MainActivity, TC and navigation_drawer.
The user enters in MainActivity in the beginning, provided his/her name and enters TC on a button click (Working perfectly fine). Here inside TC there are two buttons "Agree", "Do not Agree" as shown below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TC">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/agree"
android:text="Agree"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/not_agree"
android:text="Do not Agree"
android:layout_below="#id/agree"/>
</RelativeLayout>
Now, if the user clicks on Agree it should go to navigation_drawer and if clicked on Do not agree it should go back to MainActivity. The code for it is:
public class TC extends AppCompatActivity {
private Button Agree, NotAgree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t_c);
Agree = (Button) findViewById(R.id.agree);
NotAgree = (Button) findViewById(R.id.not_agree);
Agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TC.this, "Agree", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(TC.this, navigation_drawer.class);
startActivity(intent);
}
});
NotAgree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TC.this, "Not Agree", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(TC.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Toast was added just to check if the right method was called or no (And it is calling the right method)
The AndroidManifest.xml contains(I am not sure if this will help):
<activity android:name=".TC" android:noHistory="true"/>
<activity android:name=".navigation_drawer" />
<activity
android:name=".MainActivity"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The problem is, for some reason no matter which button I click it always redirects to navigation_drawer also for both the buttons the Toast message was shown as expected.
I do not know what am I missing here, please suggest a solution. Thank you.

I don't see anything wrong with your code and should work but it seems like you are starting the navigation_drawer activity in both button clicks.
So I suggest you declare and initialize both button's Intent variables outside the setOnClickListner() block by giving each Intent variables different name such as intent1 and intent2 and try running it again.

test this :
remove android:noHistory="true" in Manifest
and after startActivity(....) call finish()

Related

How can I enable split-screen programmatically from inside my android app through on click button

This bounty has ended. Answers to this question are eligible for a +50 reputation bounty. Bounty grace period ends in 6 hours.
M. Usman Khan wants to draw more attention to this question:
Please somebody tell us how to trigger multi-window. Specially for Android 13 and above
My app contains a button through that button just want to trigger split screen functionality
Try to use setSplitScreenState(boolean) to trigger split screen functionality
Example
inside button
onClick{
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
if(manager != null){
manager.setSplitState(true);
}
}
R.layout.activity_main (xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:onClick="startNewActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="297dp" />
</android.support.constraint.ConstraintLayout>
R.layout.activity_second (xml)
(Just a textView to keep it simple)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:text="Second Activity" />
</LinearLayout>
Then your MainActivity launch second activity from first activity when Start button is clicked and set Flags. Rect takes care of the switching in division and activity option takes care of the transiting animation;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startNewActivity(View view) {
Intent i = new Intent(this, SecondActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
Rect rt = new Rect(0, 0, 100, 100)
ActivityOptions actoptions = ActivityOptions.makeBasic();
ActivityOptions bounds = actoptions.setLaunchBounds(rt);
startActivity(i);
}
}
For this example, nothing I am going to leave the second activity as is.
SecondActivity
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Finally and most importantly MainActivity.this in your manifest.xml file should look like this;
<activity android:name=".MainActivity"
android:resizeableActivity="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
To switch into multi window mode long press on the overview button and drag the app to one side of the screen
That's all.

Button doesn't redirect to activity but crashes app instead

My button doesnt open up a new activity, the app crashes instead. I've even copied the source code from http://www.androidbegin.com/tutorial/android-button-click-new-activity-example/ and try running it on my own but still the app crashes. I cant seem to find the problem.
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the button in activity_main.xml
button = (Button) findViewById(R.id.MyButton);
// Capture button clicks
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Start NewActivity.class
Intent myIntent = new Intent(MainActivity.this,
secondActivity.class);
startActivity(myIntent);
}
});
}
}
XML BUTTON
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/MyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
YOUR CODE IS FINE!
The most likely cause of this behavior is that secondActivity is not registered in your manifest. Check whether it is and try again. If it's not, you can simply register it by adding the line below inside the application tag of your manifest.xml file.
<activity android:name=".secondActivity" />
Re-run your code and try again. It'd most likely work this time.
I hope this helps.. Merry coding!
As per the tutorial link you provided, second activity's name is NewActivity.class. In your code, it looks like you modified it to secondActivity.class.
So ensure to have it manifest also
<activity android:name=".secondActivity" >
</activity>
And always use PascalCase for Classes and camelCase for methods
Place this code snippet:
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the button in activity_main.xml
button = (Button) findViewById(R.id.MyButton);
// Capture button clicks
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Start NewActivity.class
Intent myIntent = new Intent(MainActivity.this,
secondActivity.class);
startActivity(myIntent);
}
});
}
}
Register secondActivity in manifest.xml
<activity
android:name=".secondActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" />
This may help you

Android buttons/app not working

I must be doing something very stupid. This is my second app - the first worked fine (honest).
I've just got a basic title screen with a button on it but nothing happens when I click on the button. The screen appears correctly but no response from the button - I've tried it in debug but nothing...no error, no info message, zilch (I'm using the AVD).
This is my code...
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.spyeye"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/spyEyeTheme" >
<activity
android:name="com.example.spyeye.TitleScreen"
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.example.spyeye.createNewGameActivity"
android:label="#string/app_name"
android:parentActivityName="com.example.spyeye.TitleScreen" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.spyeye.TitleScreen" />
</activity>
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".TitleScreen" >
<ImageView
android:src="#drawable/spyeyelogo"
android:contentDescription="#string/logo"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/logo" />
<Button
android:id="#+id/newBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/logo"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:onClick="newGame"
android:text="#string/newTxt" />
Java file:
public class TitleScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
}
public void newGame (View v) {
// create intent to start another activity
Intent newGameIntent = new Intent(this, createNewGameActivity.class);
startActivity(newGameIntent);
}
}
The only major difference between this and my other app is that I have now tried to use a single style file and I've re-designed my own buttons:
<style name="spyEyeTheme" parent="android:Theme.Light">
<item name="android:buttonStyle">#style/myButton</item>
</style>
<style name="myButton" parent="android:Theme.Light">
<item name="android:background">#008080</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:textSize">24sp</item>
<item name="android:typeface">sans</item>
<item name="android:padding">10sp</item>
</style>
Anyone see the obvious mistake I must have made?
Personally I am really not a big fan of that android:onClick="newGame" stuff. You should try it the good old-fashioned way, like this:
public class TitleScreen extends Activity {
private Button newBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
this.newBtn = (Button) findViewById(R.id.newBtn);
this.newBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newGameIntent = new Intent(this, createNewGameActivity.class);
startActivity(newGameIntent);
}
});
}
}
Or like this:
public class TitleScreen extends Activity implements View.OnClickListener {
private Button newBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
this.newBtn = (Button) findViewById(R.id.newBtn);
this.newBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent newGameIntent = new Intent(this, createNewGameActivity.class);
startActivity(newGameIntent);
}
}
If you are dealing with multiple Buttons you can handle them in one OnClickListener like this:
private final View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
final int id = view.getId();
switch (id) {
case R.id.newBtn:
Intent newGameIntent = new Intent(this, createNewGameActivity.class);
startActivity(newGameIntent);
break;
case R.id.otherButton:
Toast.makeText(this, "Other Button clicked!", Toast.LENGTH_SHORT).show();
break;
case R.id.cancelButton:
...
break;
}
}
};
You get the id of the calling View and use a switch to differentiate between the specific Buttons. For example in your Activity you can implement this like this:
public class TitleScreen extends Activity implements View.OnClickListener {
private Button newBtn;
private Button otherBtn;
private Button cancelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
this.newBtn = (Button) findViewById(R.id.newBtn);
this.newBtn.setOnClickListener(this);
this.otherBtn = (Button) findViewById(R.id.otherBtn);
this.otherBtn.setOnClickListener(this);
this.cancelBtn = (Button) findViewById(R.id.cancelBtn);
this.cancelBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final int id = view.getId();
switch (id) {
case R.id.newBtn:
Intent newGameIntent = new Intent(this, createNewGameActivity.class);
startActivity(newGameIntent);
break;
case R.id.otherBtn:
Toast.makeText(this, "Other Button clicked!", Toast.LENGTH_SHORT).show();
break;
case R.id.cancelBtn:
...
break;
}
}
}
A few things that caught my eye:
The names of classes are supposed to start with an upper case letter, so instead of createNewGameActivity you Activity should be called CreateNewGameActivity.
Use Fragments. The golden age of Activities is over. Since Fragments were introduced Activities are just supposed to be containers for the Fragments. So even if you just have one Button in your layout you should have an empty Activity which just contains one Fragment and in that Fragment you implement your UI and logic.
Don't use android:onClick. There is no indication in the code that this method will be called at all. And there is no reason for the layout to assume that such a method exists anywhere in the View, Fragment or Activity which loads the layout. And aside from that it isn't even that convenient. In 99,9% of all cases in which you need to set an OnClickListener you also need to do other stuff with the Button and then you need the reference anyway. android:onClick just clutters your code and makes it more confusing. it spreads implementation details out and obscures it to the developer. That the layout knows or even defines specific implementation details is in itself already pretty bad.

Do I have to start some kind of sqlite server before using it in android application

well, almost everything is in the question, I have a problem with program which should use the sqlite, it still returns the "unexpected error", I was just wondering do I have to start some kind of server, deamon or service?
androidManifest[ snippet ]
<activity android:name=".About">
android:label="#string/about_title"
android:theme="#android:style/Theme.Dialog" >
</activity>
<activity android:name=".Exit">
andorid:label="#string/exit_title">
</activity>
<activity android:name=".Options">
</activity>
<activity android:name=".Start">
</activity>
<activity android:name=".Create">
</activity>
</application>
AndroidSQLite
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sql);
TextView listContent = (TextView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.insert("ABCDE");
mySQLiteAdapter.insert("FGHIJK");
mySQLiteAdapter.insert("1234567");
mySQLiteAdapter.insert("890");
mySQLiteAdapter.insert("Testing");
mySQLiteAdapter.close();
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
String contentRead = mySQLiteAdapter.queueAll();
mySQLiteAdapter.close();
listContent.setText(contentRead);
}
sql.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
/>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
main.xml [snippet]
<Button
android:id="#+id/where_button"
android:onClick="WhereCl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/where_label" />
code responsible for button Where Am I?
mainActivity.java
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View startButton = findViewById(R.id.start_button);
View whereButton = findViewById(R.id.where_button);
View aboutButton = findViewById(R.id.about_button);
View exitButton = findViewById(R.id.exit_button);
}
public void OptionsCl(View v){
startActivity(new Intent(this,Options.class));
}
public void WhereCl(View v){
startActivity(new Intent(this,AndroidSQLite.class));
}
public void StartCl(View v){
Intent idd = new Intent(this,Start.class);
startActivity(idd);
}
public void AboutCl(View v){
startActivity(new Intent(this,About.class));
}
public void ExitCl(View v){
finish();
}
}
the error I receive is similar to this which come up with unregistred action, but the action is registred [ check the code ]
it is just "the application blabla (menu.dot) has stopped unexpectedly. Please try again" Force close.
Android SQLite is readymade library. So you don't need to start any Service, server or demon. Just to initiate a database class extending SQLite DatabaseHelper class and use it.
Thanks.

ActivityNotFoundException

Hi and thank you for reading my question. I am a new so bear with me.
I have am app that I have divided into two activities
Find the server/Login and
display a TabActivity with three web pages that are generated on the server.
I have an ImageView in both layouts that acts as a splash screen while the WebViews are loading. It is tagged "visible" while the WebView and TabViews are marked "gone".
The signIn WebView is the main entry point and loads in the background. If all is good a page with the word "symbol" is loaded. My WebViewClient is listening with the onPageFinished(WV,Str) method.
Problem:
I can not seem to successfully call the TabActivity from the signIn Activity (ActivityNotFoundException).
I have both activities listed in the Manifest.
I have done this in two of my last apps so I'm going crazy here.
I'm at the point where I may have changed too much code and have a blatant mistake. Please forgive me.
I have tried to startActivity(Intent) directly from the WVC and by calling another method startTabView() so there is extra code that is confusing.
I have tried declaring the Intent first, adding the component and calling startActivity(context, intent).
I have written the one line startActivity(new Intent("string class name")).
I feel like my intent may be null.
have a look:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
phoneID = "" + tm.getDeviceId() ;
onStart();
}
public void setLoginVisible(){
ImageView splash = (ImageView) findViewById(R.id.splash);
splash.setVisibility(View.GONE);
signIn.setVisibility(View.VISIBLE);
signIn.requestFocus();
Toast.makeText(getApplicationContext(), phoneID, Toast.LENGTH_LONG);
}
public void startTabView(){
try{
startActivity( new Intent(this,WizForex.class));
}catch (ActivityNotFoundException anf){
Toast.makeText(getApplicationContext(), anf.toString(), Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
wvc= new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (url.contains("NCdisclaimer")) setLoginVisible();
else if (url.contains("symbol")){
startTabView();
}
}
};
signIn = (WebView) findViewById(R.id.signIn);
signIn.getSettings().setJavaScriptEnabled(true);
signIn.setWebViewClient(wvc);
signIn.loadUrl("http://www.thewizard........"+ phoneID);
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- Splash View -->
<ImageView
android:id="#+id/splash"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="#drawable/splash"
android:visibility="visible"/>
<!-- signIn View -->
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/signIn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Eric.Sheasby.wiz"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="WizFinder"
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=".WizForex"
android:label="#string/app_name">
</activity>
<activity android:name=".Tester"
android:label="#string/tester">
`
Sorry this is so long. What have I done?
The problem might be that you are calling startTabView() from within an action handler (an other thread, not the ui!).
You should give a try instantiating a Handler (mHandler):
private static final int LOAD_TABVIEW = 10; //or any other number
private final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case LOAD_TABVIEW:
startTabView();
break;
default:
break;
}
};
};
and in your onPageFinished(WebView view, String url) method you should change a line
startTabView();
to
//send message to the handler:
mHandler.sendEmptyMessage(LOAD_TABVIEW);
This way your mHandler's handleMessage gets called, and it should start the TabView.

Categories

Resources