I have 7 Activities in my application. I wants to display admob in every activity
Whether i have to create each AdView in every activity?
or
is there any alternative to reuse previous activity container OR prevent it from destroy so can i use in next activity....
Any code or hint we'll b appreciate.
Thankx
I DID this. Thankx to yorkw comment. This is not an efficient code. But you can modify accordingly. That reduces your code for each activity.
Just Extends "TestingAdmobActivity" & call SetupAds() to call your advs.
My SuperClass "TestingAdmobActivity.java"
package com.test.myadmob;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
public class TestingAdmobActivity extends Activity implements AdListener{
public AdView adView;
public String ADV_PUB_ID = "a14e2fb60918999";
private boolean adVisible = true;
LinearLayout layout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Admob", "Calling External");
}
public void SetupAds(){
Log.i("AdMob", "Start Setup");
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL); //To put AdMob Adv to Bottom of Screen
Log.i("AdMob", "End Layout Setup");
addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
adView = new AdView(this, AdSize.BANNER, ADV_PUB_ID);
adView.setAdListener(this);
Log.i("AdMob", "Init complete Adview");
layout.addView(adView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("AdMob", "Done AddView Layout");
AdRequest request = new AdRequest();
request.addTestDevice(AdRequest.TEST_EMULATOR);
request.addKeyword("LifeOK");
adView.loadAd(request);
Log.i("AdMob", "End Setup");
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 0: //Disable Adv
if (adVisible)
adVisible = false;
break;
case 1: //Enable Adv
if (!adVisible)
{
Log.i("AdMob", "Case 1");
adVisible = true;
}
break;
case 2: //Enable but Hide Adv
adView.setVisibility(View.GONE);
break;
case 3: //Enable but Show Adv
adView.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
};
public void DisableAds()
{
Log.i("AdMob", "Request Disable Adv");
handler.sendEmptyMessage(0);
}
public void EnableAds()
{
Log.i("AdMob", "Request Enable Adv");
handler.sendEmptyMessage(1);
}
public void HideAdv() //Enable Adv but Hide
{
Log.i("AdMob", "Request Hide Adv");
handler.sendEmptyMessage(2);
}
public void ShowAdv() //Show Adv
{
Log.i("AdMob", "Request Show Adv");
handler.sendEmptyMessage(3);
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Dismiss Screen");
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
Log.d("AdMob", "failed to receive ad (" + arg1 + ")");
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Leaving Application");
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Present Screen");
}
#Override
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Adv Received");
}
}
My FirstActivityClass "NewActivity_1.java"
package com.test.myadmob;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class NewActivity_1 extends TestingAdmobActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Admob", "OnCreate");
SetupAds();
Log.i("Admob", "Done");
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Admob", "Going to Activity 2");
Intent mainIntent = new Intent().setClass(NewActivity_1.this, NewActivity_2.class);
startActivity(mainIntent);
}
});
}
}
My SecondActivityClass "NewActivity_2.java"
package com.test.myadmob;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class NewActivity_2 extends TestingAdmobActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Admob", "OnCreate");
SetupAds();
Log.i("Admob", "Done");
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Admob", "Going Back to Activity 1");
finish();
}
});
}
}
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.myadmob"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".NewActivity_1" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TestingAdmobActivity" ></activity>
<activity android:name=".NewActivity_2" ></activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
>
</activity>
</application>
<!-- AdMob SDK requires Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- to get Android Device ID -->
</manifest>
Note: for the sake of permissions used by google admob sdk, i have to build this on android 4.0 sdk with min-sdk version 7
In my app I have a cache of 0..12 ads at any given time. I'm reusing them accross different Fragments in an endless ViewPager. The caching class is in charge of loading the providing the ads to the Fragments.
The trick is to:
Call the AdView's onDestory only when you're sure you're done with that AdView instance for good. This means that the Fragments themselves are not in charge of this.
Passing the AdView's themselves between the Fragments, we need to remember to detach each AdView from its hierarchy:
(only on the UI thread of course):
public void detachFromHirerchy()
{
View adView = getAdView();
if ( adView != null )
{
ViewGroup parent = (ViewGroup) adView.getParent();
if (parent != null)
{
parent.removeView( adView );
}
}
}
Related
I have an application with two Activitys.
The first Activity starts the second Activity on a Button click. In the second Activity, after I call finish(), also on a Button click, I expect that the application will return to the first Activity.
What happen is that the application gets minimized (goes in background). The device on which I am developing is a Sony Xperia Z2 with Android 4.4.2.
Is this an Android issue or is it something wrong that I am doing in code?
The manifest file:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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.example.test.SecondActivity">
</application>
First activity onClick:
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
});
Second activity onClick:
btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
First thing is that it is not a Android issue.
Secondly, please make sure you have not finished your first Activity when you are moving from First to Second.
If you are doing this in first class:
Intent in=new Intent(A.this, B.class);
startActivity(in);
this.finish();
then remove this.finish(); because it finishes up your first Activity and when you are coming back from second then first Activity is not present in the stack. So how it would be called.
First.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class First extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Second.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
basically am a java developer but now am developing an android app.In my app i can't redirect to the next page when i click on to SIGN IN button and here is my code
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button log,sign;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
log = (Button) findViewById(R.id.login);
sign = (Button) findViewById(R.id.signup);
log.setOnClickListener(this);
sign.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.login:
break;
case R.id.signup:
Intent open = new Intent("com.example.eblood.Register");
startActivity(open);
break;
}
}
}
}
Here is my next page java code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Register extends Activity{
Button backlog,regg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
backlog = (Button) findViewById(R.id.linktologin);
regg = (Button) findViewById(R.id.register);
backlog.setOnClickListener((OnClickListener) this);
}
public void onClick (View v)
{
switch(v.getId()) {
case R.id.register:
break;
case R.id.linktologin:
Intent in = new Intent("com.example.eblood.MainActivity");
startActivity(in);
break;
}
}
}
Here is my manifest code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.eblood"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.eblood.home"
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.eblood.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.eblood.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.eblood.Register"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.REGISTER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
and the error am getting is android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.eblood.Register }
And here is my home.java
package com.example.eblood;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class home extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Thread timer = new Thread(){
public void run(){
try{
sleep(2000);
} catch (InterruptedException e){
e.printStackTrace();
} finally {
Intent openMainActivity = new Intent("com.example.eblood.MAINACTIVITY");
startActivity(openMainActivity);
}
}
};
timer.start();}{
}
}
Try this..
If you use Intent open = new Intent("com.example.eblood.Register"); you will get ActivityNotFoundException change it as Intent open = new Intent(MainActivity.this,Register.class);
Change this
Intent open = new Intent("com.example.eblood.Register");
startActivity(open);
to
Intent open = new Intent(MainActivity.this,Register.class);
startActivity(open);
also
change this
Intent in = new Intent("com.example.eblood.MainActivity");
startActivity(in);
to
Intent in = new Intent(Register.this,MainActivity.class);
startActivity(in);
EDIT
Change this.
Intent openMainActivity = new Intent("com.example.eblood.MAINACTIVITY");
startActivity(openMainActivity);
to
Intent openMainActivity = new Intent(home.this,MainActivity.class);
startActivity(openMainActivity);
I have made a simple android program with two activities,in that 1st activity contains an edittext and a button,and second activity contain a textview.Now when the button in 1st activity pressed the text from Edittext should go to 2nd activity's textView.I have tried code as below,but it's not working:
MainActivity.java
package com.example.myweb;
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.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myweb";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b =(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText ed = (EditText)findViewById(R.id.edit_msg);
Intent i = new Intent(getApplicationContext(),Act2.class);
String s= ed.getText().toString();
i.putExtra("EXTRA_MESSAGE", s);
startActivity(i);
}
});
}
}
Act2.java
package com.example.myweb;
import org.w3c.dom.Text;
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.EditText;
import android.widget.TextView;
public class Act2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView tv = (TextView)findViewById(R.id.tv1);
Intent i =getIntent();
String msg = i.getStringExtra(MainActivity.EXTRA_MESSAGE);
tv.setText(msg);
setContentView(tv);
}
});
}
}
please help me.thank you
Just try this:
In MainActivity.java:
declare Button b and EditText ed as a class field (i.e. keep it outside onCreate())
class MainActivity.java
{
Button b;
EditText ed;
...
onCreate() {
...
b =(Button)findViewById(R.id.button1);
ed = (EditText)findViewById(R.id.edit_msg);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,Act2.class);
String s= ed.getText().toString();
i.putExtra("EXTRA_MESSAGE", s);
startActivity(i);
}
});
...
In Act2.java:
...
Intent i = getIntent();
String msg = i.getStringExtra("EXTRA_MESSAGE");
TextView tv = (TextView)findViewById(R.id.tv1);
tv.setText(msg);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
...
You are using
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
So, in MainActivity
i.putExtra(EXTRA_MESSAGE, s);
startActivity(i);
(OR)
String message = intent.getStringExtra("EXTRA_MESSAGE");
also,
i.putExtra("EXTRA_MESSAGE", s);
Change
String msg = i.getStringExtra(MainActivity.EXTRA_MESSAGE);
to
String msg = i.getStringExtra("EXTRA_MESSAGE");
MainActivity.EXTRA_MESSAGE would mean a static variable of MainActivity.java class. Hope you get the difference. You need the variable EXTRA_MESSAGE which you had put in intent i
Edit: For your crash, we need a logcat o/p and activity, manifest code. But possible reasons:
Activity Act2.java is not declared in manifest file.
You said you have only a textview in second activity. But you are trying to get button1 from act2.xml. So you are getting Force close.
Change Act2.java 's onCreate() as
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
TextView tv = (TextView)findViewById(R.id.tv1);
Intent i =getIntent();
String msg = i.getStringExtra("EXTRA_MESSAGE");
tv.setText(msg);
}
You don't need to call setContentView(tv); as it is already there in act2.xml and you are using setContentView(R.layout.act2);
Hope your problem gets solved.
Use this code
**MainActivity.java**
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button1);
final EditText editText = (EditText)findViewById(R.id.editText1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("EXTRA_MESSAGE", editText.getText().toString());
startActivity(intent);
}
});
}
}
**activity_main.xml**
<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=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="74dp"
android:layout_marginTop="26dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:layout_marginLeft="69dp"
android:layout_marginTop="47dp"
android:text="Button" />
</RelativeLayout>
**SecondActivity.java**
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.second);
Intent intent = getIntent();
final String message = intent.getStringExtra("EXTRA_MESSAGE");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView textView = new TextView(SecondActivity.this);
textView.setText(message);
setContentView(textView);
}
});
}
}
**second.xml**
<?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:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tester"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.tester.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=".SecondActivity"></activity>
</application>
</manifest>
Try
Intent i = new Intent(MainActivity.this,Act2.class);
You are using
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
So, in MainActivity
i.putExtra(EXTRA_MESSAGE, s);
startActivity(i);
please review and change your code its works
package com.example.activityact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b =(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText ed = (EditText)findViewById(R.id.editText1);
Intent i = new Intent(getApplicationContext(),Act2.class);
String s= ed.getText().toString();
i.putExtra("EXTRA_MESSAGE", s);
startActivity(i);
}
});
}
}
Act2.java
package com.example.activityact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class Act2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
// TODO Auto-generated method stub
TextView tv = (TextView) findViewById(R.id.textView1);
Intent i =getIntent();
// String msg = i.getStringExtra(EXTRA_MESSAGE);
//String receiver = getIntent().getStringExtra(EXTRA_MESSAGE);
String message = i.getStringExtra("EXTRA_MESSAGE");
tv.setText(message);
}
}
Value of the EXTRA_MESSAGE variable in MainActivity.java is different then the key value that you are putting message in to intent.
MainActivity.java:
public final static String EXTRA_MESSAGE = "com.example.myweb";
i.put("EXTRA_MESSAGE",s);
Act2.java: (you are accessing by extra_message variable which is not correct)
Intent i = getIntent();
String text = i.getStringExtra(MainActivity.EXTRA_MESSAGE); //WHICH IS DIFFER FROM THE KEY VALUE
So key value should be the same at the time of setting and getting the value. here while setting the value key is "EXTRA_MESSAGE" and while getting "com.example.myweb" so you will get null pointer exception.
SOLUTION:
just change the line in Act2.java
Intent i = getIntent();
String text = i.getStringExtra("EXTRA_MESSAGE");
Also check your menifest file for the activities declaration.
Hope it may help you.
Did you remember to correctly define your second activity in the manifest XML?
Check out this great guide for anything else you might have missed: http://developer.android.com/training/basics/firstapp/starting-activity.html
I was studying of Onclick events and the listeners in android. On the way, I created a sample app and my aim is to save the given number (register.java) in the database and to show it in an another activity (main.java). But, now on clicking the 'save' button, nothing has been happening. Even the toast method is also not working.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
data = register.this.openOrCreateDatabase("Number", MODE_PRIVATE, null);
data.execSQL("CREATE TABLE IF NOT EXISTS table1(number varchar(15));");
e1 = (EditText)findViewById(R.id.mob_num);
b1 = (Button)findViewById(R.id.save);
b2 = (Button)findViewById(R.id.go);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
number = e1.getText().toString();
data.execSQL("INSERT INTO table1 VALUES('"+number+"')");
Toast.makeText(getApplicationContext(), "'"+number+"'successfully inserted",Toast.LENGTH_SHORT).show();
Intent i = new Intent(register.this, main.class);
startActivity(i);
finish();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(register.this,main.class);
startActivity(i);
data.close();
finish();
}
});
}
Here is my manifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="a.a.a"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name=".main"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</activity>
</application>
</manifest>
I know this a very basic thing in android. But, I hope you may help me in this. Sorry and Thanks for your time.
There's an easy way to register onClickListeners in Android:
In your declaration of the button add
android:onClick="onClick" and create a method in the Activity containing the button called onClick(View v). From here you can just
switch(v) {
case R.id.save:
Toast.makeText(this, "save button has been pressed", Toast.LENGTH_LONG).show();
break;
case R.id.go:
Toast.makeText(this, "go button has been pressed", Toast.LENGTH_LONG).show();
break;
}
and so on until you've registered all the buttons in the activity. Of course you can use other variable names than what I did in this example, just remember the onClick method (or whatever you name it) MUST be called with View as parameter and the switch MUST run on that parameter.
Just try this simple approach to check button click and tell me if it works:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button closeButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.closeButton = (Button)this.findViewById(R.id.button);
this.closeButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(this, "You clicked the button", Toast.LENGTH_SHORT).show();
}
}
Button btn,
btnback = (Button) findViewById(R.id.activity_essentials_btnback);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(v.getContext(), "Click here",
Toast.LENGTH_SHORT).show();
}
});
The Logcat provided does not give any information, Provide the correct logcat.
The code for the click listeners is right. The probable exception is only the null pointer exception. So provide null checks to all the data base creation and insertion.
I am developing app for displaying a channel's live stream and it starts on landscape mode by default and I can change it to portrait and vice versa from my options menu
Now I am using this code in manifest and put it in that activity
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
When I start app, it is working fine but when I change orientation to portrait, the app is hanging and options menu doesn't disappear as usual.
if I deleted this part |screenSize from manifest, it is working fine but the layout-land doesn't work and portrait layout is used at both orientation.
This is LiveActivity.java
package com.shadatv.shada;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.VideoView;
public class LiveActivity extends Activity {
VideoView videoView;
private AlertDialog.Builder errorDialog;
String httpLiveUrl = "http://38.96.148.147:1935/live/livestream/playlist.m3u8";
// =============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setContentView(R.layout.live);
try {
videoView = (VideoView) findViewById(R.id.myVideoView);
videoView.setVideoURI(Uri.parse(httpLiveUrl));
videoView.requestFocus();
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
videoView.seekTo(1000);
videoView.start();
}
});
} catch (Exception e) {
errorDialog = new AlertDialog.Builder(this);
errorDialog.setMessage("مشكلة في البث");
errorDialog.setCancelable(true);
errorDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog errorStream = errorDialog.create();
errorStream.show();
}
}
// =============================================================================
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_shada, menu);
MenuItem fullItem = menu.findItem(R.id.fullScreen);
MenuItem smallItem = menu.findItem(R.id.smallScreen);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
fullItem.setVisible(false);
smallItem.setVisible(true);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
smallItem.setVisible(false);
fullItem.setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
// =============================================================================
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// setContentView(R.layout.activity_shada);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// setContentView(R.layout.activity_shada1);
}
}
// =============================================================================
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about: {
// TODO Auto-generated method stub
startActivity(new Intent("com.shadatv.MainActivity"));
}
break;
case R.id.smallScreen: {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
break;
case R.id.fullScreen: {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
break;
}
return true;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shadatv.shada"
android:versionCode="3"
android:versionName="1.0.2" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/shada"
android:label="#string/app_name"
>
<activity
android:name=".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=".LiveActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:exported="false"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="com.shadatv.LiveActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</manifest>
I solved it by pull out the setContentView and try/catch block from onCreate and put it onConfigChanged
package com.shadatv.shada;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.VideoView;
public class LiveActivity extends Activity {
VideoView videoView;
private AlertDialog.Builder errorDialog;
String httpLiveUrl = "http://38.96.148.147:1935/live/livestream/playlist.m3u8";
// =============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// if (getResources().getConfiguration().orientation ==
// Configuration.ORIENTATION_LANDSCAPE) {
// getWindow().clearFlags(
// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// }
// setContentView(R.layout.live);
}
// =============================================================================
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_shada, menu);
MenuItem fullItem = menu.findItem(R.id.fullScreen);
MenuItem smallItem = menu.findItem(R.id.smallScreen);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
fullItem.setVisible(false);
smallItem.setVisible(true);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
smallItem.setVisible(false);
fullItem.setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
// =============================================================================
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.live);
try {
videoView = (VideoView) findViewById(R.id.myVideoView);
videoView.setVideoURI(Uri.parse(httpLiveUrl));
videoView.requestFocus();
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
videoView.seekTo(1000);
videoView.start();
}
});
} catch (Exception e) {
errorDialog = new AlertDialog.Builder(this);
errorDialog.setMessage("مشكلة في البث");
errorDialog.setCancelable(true);
errorDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog errorStream = errorDialog.create();
errorStream.show();
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
// =============================================================================
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
// TODO Auto-generated method stub
startActivity(new Intent("com.shadatv.MainActivity"));
break;
case R.id.smallScreen:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case R.id.fullScreen:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
return true;
}
}
But I find out another problem at optionsMenu. When I press about button to get out from this activity and run MainActivity, the app stops. What is wrong?
When you write android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself.
so the portrait layout will not set on your activity when the screen orientation changed.
why you are using android:configChanges="keyboardHidden|orientation ?