I'm making an Android Browser Application. Its splash image opens after loading but afterward it crashes. I haven't found what mistake I have in MainActivity.java code.
When i run the code, my default AVD tells me that my application has crashed.
MainActivity.java
package com.example.package;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity
extends Activity
{
private WebView a;
#SuppressLint({"InlinedApi"})
private BroadcastReceiver b = new a(this);
public void a()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Google");
localBuilder.setMessage("Are you sure you want to Exit?");
localBuilder.setIcon(2130837505);
localBuilder.setPositiveButton("YES", new d());
localBuilder.setNegativeButton("NO", new e());
localBuilder.show();
}
public void onBackPressed()
{
a();
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(2);
setContentView(2130903042);
this.a = ((WebView)findViewById(2131230720));
this.a.getSettings().setJavaScriptEnabled(true);
this.a.setFocusableInTouchMode(true);
this.a.getSettings().setLoadWithOverviewMode(true);
this.a.getSettings().setUseWideViewPort(true);
this.a.getSettings().setLoadsImagesAutomatically(true);
this.a.loadUrl("http://www.google.com");
this.a.setWebChromeClient(new b(this));
this.a.setDownloadListener(new c());
this.a.setWebViewClient(new f());
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
super.onCreateOptionsMenu(paramMenu);
paramMenu.add(0, 1, 0, "Home").setIcon(2130837506);
paramMenu.add(0, 2, 0, "Downloads").setIcon(2130837504);
paramMenu.add(0, 3, 0, "Back").setIcon(2130837506);
paramMenu.add(0, 4, 0, "Forward").setIcon(2130837505);
paramMenu.add(0, 5, 0, "Refresh").setIcon(2130837509);
return true;
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
{
if ((paramInt == 4) && (this.a.canGoBack()))
{
this.a.goBack();
return true;
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
super.onOptionsItemSelected(paramMenuItem);
switch (paramMenuItem.getItemId())
{
default:
return false;
case 1:
this.a.loadUrl("http://www.google.com");
return true;
case 3:
this.a.goBack();
return true;
case 5:
this.a.reload();
return true;
case 4:
this.a.goForward();
return true;
}
}
protected void onPause()
{
super.onPause();
unregisterReceiver(this.b);
}
#SuppressLint({"InlinedApi"})
protected void onResume()
{
IntentFilter localIntentFilter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
registerReceiver(this.b, localIntentFilter);
super.onResume();
}
}
a.java
package com.example.package;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.widget.Toast;
class a
extends BroadcastReceiver
{
a(MainActivity paramMainActivity) {}
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, paramContext.getResources().getString(2131034114), 0).show();
}
public static void finish() {
// TODO Auto-generated method stub
}
public static void startActivity(Intent localIntent) {
// TODO Auto-generated method stub
}
}
g.java
package com.example.package;
import android.app.Activity;
import android.content.Intent;
import java.util.TimerTask;
class g
extends TimerTask
{
private Object a;
g(splash paramsplash) {}
public void run()
{
((Activity) this.a).finish();
Intent localIntent = new Intent();
((Activity) this.a).startActivity(localIntent);
}
}
Your problem is almost certainly the issue:
this.a = ((WebView)findViewById(2131230720));
The number "2131230720" is a static reference int to resources, in this case a layout view in your Activity. That number comes from R.java which is created when you "build" your project. Each time you perform a build, it will assign an integer to layout objects, strings, etc. that you define in XML in your res folder.
Using the integer value might work for a while (or is present in source code), but then you change your layouts (or other R objects like strings) or rebuild on a different machine, Android library, etc. and it doesn't work anymore;
That line should look like this:
this.a = ((WebView)findViewById(R.id.my_webview_layout_id));
where "my_webview_layout_id" is from your layout XML file. You should find the "id" of the XML defined object in an XML file in res/layout Use that #+id reference. That will keep track of changes to that static reference.
Then when you build or rebuild your Android app, it will create the R.java file with all of the appropriate references.
Related
I'm struggling with why this code won't compile, I'm trying to get the current wallpaper, then change it, then give the option to change it back.
Below is my code, it doesn't compile because it can't resolve symbol 'context' and it says my drawable cannot be converted to an integer which doesn't make any sense whatsoever.
I'm trying to change the drawable to a bitmap AND I have imported the import
android.content.Context
so what is it I am doing wrong here?? this is my code, the onClick stores the wallpaper and starts the change activity, the onPush method resets the wallpaper and exits the app, any help would be appreciated thanks!
import android.content.Context;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import java.io.IOException;
import static android.app.WallpaperManager.*;
public class SetWallpaperActivity extends Activity {
public Drawable originalWallpaper;
public Bitmap paper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
originalWallpaper = wm.getDrawable();
paper1 = BitmapFactory.decodeResource(context.getResources(),
originalWallpaper);
Intent intent = new Intent(
ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
}
public void onPush(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
WallpaperInfo wallpaperInfo = wm.getWallpaperInfo();
if (wallpaperInfo != null) {
try {
wm.setBitmap(paper1);
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
System.exit(0);
}
}
This is the error code I'm getting:
'decodeResource(android.content.res.Resources, int)' in 'android.graphics.BitmapFactory' cannot be applied to '(android.content.res.Resources, android.graphics.drawable.Drawable)'
package com.example.nimehr.streaming;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.videostream.VideoViewActivity;
public class MainActivity extends Activity {
Button button;
public MainActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(2130903040);
this.button = (Button)this.findViewById(R.id.myButton);
this.button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, VideoViewActivity.class);
MainActivity.this.startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
this.getMenuInflater().inflate(2131165184, menu);
return true;
}
}
I'm getting the error "Expected resource of type layout/menu" at 2130903040 in this.setContentView(2130903040); and 2131165184in this.getMenuInflater().inflate(2131165184, menu); respectively. I fixed it here this.button = (Button)this.findViewById(2131230720); by changing it to R.id.MyButton
DO not do it this way:
this.setContentView(2130903040);
R class exists for a reason to avoid explicitly using ids like this, and to replace it with a more readable cleaner code:
this.setContentView(R.layout.layout_name_here);
From the docs:
When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory.
I'm importing a windows pairs game (writen in java) to android
but when I run this I can see no buttons...
(currently my code does not seems nice cuz I shoud deliver it to uni fast)
what is going wrong here?
package mgh;
import mgh.mgh.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.RelativeLayout;
public class mghActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new mghActivity();
}
public int numberOfClickes=0;
public card continueCard=null;
public int killedCards=0;
public card selectedCard=null;
public long spentTime=0;
public card[][] card=new card[4][4];
public void mghActivity(){
setTitle("pairs");
//setVisible(true);
//setSize(500,500 );
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AbsoluteLayout lay=new AbsoluteLayout(this);
int[] clr=new int[8];
short[] timesUsed=new short[8];
for (int i=0;i<=7;i++)
timesUsed[i]=0;
for (int i=0;i<=7;i++)
clr[i]= Color.rgb(((int)(Math.random()*2))*255,
((int)(Math.random()*2))*255,
((int)(Math.random()*2))*255);
for (int i=0;i<=3;i++)
for (int j=0;j<=3;j++){
int rnd=0;
while (timesUsed[rnd]>=2)
rnd=(int)(Math.random()*8)%8;
timesUsed[rnd]++;
card[i][j]=new card(this,clr[rnd]);
//card[i][j].setEnabled(false);
//AbsoluteLayout.LayoutParams mparams=new AbsoluteLayout.LayoutParams
//(lay.getWidth()/4,lay.getHeight()/4,(lay.getWidth()/4)*i,(lay.getWidth()/4)*j);
int m=40;
AbsoluteLayout.LayoutParams mparams=new AbsoluteLayout.LayoutParams
(m,m,m*i,m*j);
lay.addView(card[i][j],mparams);
card[i][j].setOnClickListener(this);
}
setContentView(lay);
}
public void onClick(View arg0) {
}
}
class card extends Button {///not completed
public int color;
public card(Context context,int color){
super(context);
this.color=color;
setBackgroundColor(color);
}
}
In method onCreate, you just new mghActivity but did not call the the method mghActivity. And mghActivity is not a constructor. You shall remove the void before mghActivity. Then it will be a constructor and called automatically. Even so, I will not recommend creating an Activity like this.
I'm new to Java, Android and JUnit. I want to learn how to write JUnit tests for an Android application. To that end, I have a very simple Android app (2 activities, 2 buttons, each button goes to the other activity). I want to test the button. This app runs fine on my phone when it's plugged in. I've been looking at the samples provided in the SDK, and I am trying to emulate them.
My problem is that when I right-click on my test project, and choose Run As -> Android JUnit test, nothing happens. I don't know why.
My test code.
package com.example.twoactivities.test;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import com.example.twoactivities.MainActivity;
import com.example.twoactivities.MainActivity2;
public class ClickButton extends ActivityInstrumentationTestCase2<MainActivity> {
private Button mButton2;
private long TIMEOUT_IN_MS = 100000;
public ClickButton() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
final MainActivity a = getActivity();
// ensure a valid handle to the activity has been returned
assertNotNull(a);
}
#SmallTest
public void click(){
// Set up an ActivityMonitor
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity2.class.getName(), null, false);
//check if button is enabled
assertTrue("button is enabled", mButton2.isEnabled());
//click button
mButton2.performClick();
MainActivity2 MainActivity2 = (MainActivity2) activityMonitor.waitForActivityWithTimeout(TIMEOUT_IN_MS );
assertNotNull("MainActivity2 is null", MainActivity2);
// assertEquals("Monitor for MainActivity2 has not been called", 1, activityMonitor.getHits());
// assertEquals("Activity is of wrong type", MainActivity2.class, MainActivity2.getClass());
// Remove the ActivityMonitor
getInstrumentation().removeMonitor(activityMonitor);
}
// public void tearDown() {
// }
}
(I know it's really simple, but I'm just trying to get the basics down.)
My application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
}
Activity 2 of my application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
Any ideas why my test class doesn't run?
Thanks,
Stephanie
You have to right click on the test itself, not the project.
According to documentation Android testing API supports JUnit 3 code style, but not JUnit 4. Try naming your test method testClick
I'm very new to android. I want to create an application that turns off all sounds at the selected time. I created a service with some code and in Eclipse there's no errors, but when I press the button nothing happens. I can see in Application Manager that my program and the service SilentHours are running. Here's my code:
MainActivity.java
package com.example.silencecontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_NAME = "sending silentHour value to service SilenceHours";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setSilenceHours(View view) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
TextView textView1 = (TextView)findViewById(R.id.textView1);
if(editText1.length() > 0) {
Intent intent = new Intent(this, SilentHours.class);
String editText1String = editText1.getText().toString();
int silentHour = Integer.parseInt(editText1String);
intent.putExtra(EXTRA_NAME, silentHour);
this.startService(intent);
} else {
textView1.setText("Please enter the silence hour. ");
}
}
}
SilentHours.java
package com.example.silencecontrol;
import java.util.Calendar;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
public class SilentHours extends Service {
public SilentHours() {
}
protected void onHandleIntent(Intent intent) {
int silentHour = Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_NAME));
Calendar calendar = Calendar.getInstance();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if(currentTime >= silentHour) {
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
And by the way I can't #Override the onHandleIntent method. If I put the #Override annotation I get error:
The method onHandleIntent(Intent) of type SilentHours must override or implement a supertype method.
Is that annotation necessary?
The method you are looking for is named onStartCommand, not onHandleIntent.
And no, it's not necessary to add this annotation to an overriden method, it's just a very good practice as you can get sure that you respected the signature of the super class.
Let you IDE help you when you code. Simply type "on" then ask for completion to see which method you can override.