Cant get my app to work. Just crashes - java

I'm trying to learn to build Android apps. This is my very first attempt. Everything was okay and when I would get to this activity (this is when someone would select rock) I could have it display Hello World. I tried to develop rules for winning and losing but whenever I select rock my app just crashes. Please take a look.
package ro.pa.sc;
import java.util.Random;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Rockvs extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
randombox();
setContentView(R.layout.activity_rockvs);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.rockvs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up- vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void randombox()
{
Random r = new Random();
int pickedNumber=r.nextInt(2);
if (pickedNumber==1) {
win();
} else if (pickedNumber==2) {
lose();
} else if (pickedNumber==0){
tie();
}
}
public void win() {
String message = "Computer picked Scissors! You Won!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
public void lose() {
String message = "Computer picked Paper! You Lose!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
public void tie() {
String message = "Computer picked Rock! It's a Tie!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
}
Logcat output:
05-05 19:22:46.571: D/ActivityThread(15646): setTargetHeapUtilization:0.25
05-05 19:22:46.571: D/ActivityThread(15646): setTargetHeapIdealFree:8388608
05-05 19:22:46.581: D/ActivityThread(15646): setTargetHeapConcurrentStart:2097152
05-05 19:22:46.722: I/Adreno200-EGL(15646): <qeglDrvAPI_eglInitialize:269>: EGL 1.4 QUALCOMM build: (CL2803123)
05-05 19:22:46.722: I/Adreno200-EGL(15646): Build Date: 11/28/12 Wed
05-05 19:22:46.722: I/Adreno200-EGL(15646): Local Branch: D1L_JB_1736J_Disable_CPUMempool
05-05 19:22:46.722: I/Adreno200-EGL(15646): Remote Branch:
05-05 19:22:46.722: I/Adreno200-EGL(15646): Local Patches:
05-05 19:22:46.722: I/Adreno200-EGL(15646): Reconstruct Branch:
05-05 19:22:48.233: W/dalvikvm(15646): threadid=1: thread exiting with uncaught exception (group=0x4126c438)
05-05 19:22:48.253: E/AndroidRuntime(15646): FATAL EXCEPTION: main
05-05 19:22:48.253: E/AndroidRuntime(15646): java.lang.RuntimeException: Unable to start activity ComponentInfo{ro.pa.sc/ro.pa.sc.Rockvs}: android.view.InflateException: Binary XML file line #11: Error inflating class <unknown>
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2080)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2105)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread.access$600(ActivityThread.java:137)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1203)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.os.Looper.loop(Looper.java:137)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread.main(ActivityThread.java:4904)
05-05 19:22:48.253: E/AndroidRuntime(15646): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 19:22:48.253: E/AndroidRuntime(15646): at java.lang.reflect.Method.invoke(Method.java:511)
05-05 19:22:48.253: E/AndroidRuntime(15646): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
05-05 19:22:48.253: E/AndroidRuntime(15646): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
05-05 19:22:48.253: E/AndroidRuntime(15646): at dalvik.system.NativeStart.main(Native Method)
05-05 19:22:48.253: E/AndroidRuntime(15646): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class <unknown>
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
05-05 19:22:48.253: E/AndroidRuntime(15646): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-05 19:22:48.253: E/AndroidRuntime(15646): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:321)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.Activity.setContentView(Activity.java:2087)
05-05 19:22:48.253: E/AndroidRuntime(15646): at ro.pa.sc.Rockvs.onCreate(Rockvs.java:20)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.Activity.performCreate(Activity.java:5232)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2044)
05-05 19:22:48.253: E/AndroidRuntime(15646): ... 11 more
05-05 19:22:48.253: E/AndroidRuntime(15646): Caused by: java.lang.reflect.InvocationTargetException
05-05 19:22:48.253: E/AndroidRuntime(15646): at java.lang.reflect.Constructor.constructNative(Native Method)
05-05 19:22:48.253: E/AndroidRuntime(15646): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
05-05 19:22:48.253: E/AndroidRuntime(15646): ... 24 more
05-05 19:22:48.253: E/AndroidRuntime(15646): Caused by: android.content.res.Resources$NotFoundException: File You picked Rock! I hope you win! from drawable resource ID #0x7f050009: .xml extension required
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.content.res.Resources.loadColorStateList(Resources.java:2094)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.content.res.TypedArray.getColorStateList(TypedArray.java:342)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.widget.TextView.<init>(TextView.java:820)
05-05 19:22:48.253: E/AndroidRuntime(15646): at android.widget.TextView.<init>(TextView.java:489)
05-05 19:22:48.253: E/AndroidRuntime(15646): ... 27 more
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=".Rockvs" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/pickedrock"
android:textColor="#string/pickedrock"
android:textSize="25sp" />
</RelativeLayout>

In your XML, the line:
android:textColor="#string/pickedrock"
is not correct - it should point to a color resource, not a string.

Related

Display random month from a button click on android?

I am trying to create an app that lets the user click a button and it will display a random month. I have created a string array in my strings.xml file. Bellow is my main.java, strings.xml and activity.xml. I try to run the app and it just force closes.
package com.example.datebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class Main extends Activity
{
Button btn;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}
}
here is my activity.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"
>
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="updateMonth"
android:text="#string/app_name" />
<TextView
android:id="#+id/text1"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="#array/Months" />
</LinearLayout>
here is my strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DateButton</string>
<string-array name="Months">
<item>January</item>
<item>Feburary</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>
</resources>
I'm still getting errors and the app still says unfortunately your app closed. The logcat is below.
09-11 16:55:17.472: W/Resources(1638): Converting to string: TypedValue{t=0x1/d=0x7f0c0000 a=-1 r=0x7f0c0000}
09-11 16:55:17.512: D/AndroidRuntime(1638): Shutting down VM
09-11 16:55:17.512: W/dalvikvm(1638): threadid=1: thread exiting with uncaught exception (group=0xb3a8fba8)
09-11 16:55:17.532: E/AndroidRuntime(1638): FATAL EXCEPTION: main
09-11 16:55:17.532: E/AndroidRuntime(1638): Process: com.example.datebutton, PID: 1638
09-11 16:55:17.532: E/AndroidRuntime(1638): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datebutton/com.example.datebutton.Main}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Handler.dispatchMessage(Handler.java:102)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Looper.loop(Looper.java:136)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invoke(Method.java:515)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-11 16:55:17.532: E/AndroidRuntime(1638): at dalvik.system.NativeStart.main(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.example.datebutton.Main.onCreate(Main.java:24)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Activity.performCreate(Activity.java:5231)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-11 16:55:17.532: E/AndroidRuntime(1638): ... 11 more
You forgot to add the line: setContentView(R.layout.activity); before trying to instantiate your button object btn.
To use layout in you Activity you have to connect them both together. Below is how your code should look like:
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int r, g, b;
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}

android app crashes when a button is pressed

I made an app and a part of the app is to get the longitude and latitude add these into one string and use that string to get an xml file from the weather servers so you can see what weather, temperature, humidity... it is at your place.
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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/instruction_nexttobutton_english" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:onClick="getPositionAndGetWheater"
android:text="#string/getweather_button_english" />
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="115dp"
android:layout_alignLeft="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2" />
</RelativeLayout>
MainActivity.java:
package com.example.thelexapp;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
#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 getPositionAndGetWheater(View view) {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String longitudestring = String.valueOf(longitude);
String latitudestring = String.valueOf(latitude);
String URLforweather = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=" + longitudestring + "," + latitudestring + "&format=xml&num_of_days=1&key=IHAVEAAPIKEYBUTI'MNOTPOSTINGITONTHEFORUMFORSECURITYREASONS";
WebView webview=(WebView)findViewById(R.id.webview);
webview.loadUrl(URLforweather);
}
}
"appname" Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.thelexapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.thelexapp.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>
</application>
</manifest>
LOGCAT WINDOWS:
02-26 15:00:26.710: D/dalvikvm(977): Not late-enabling CheckJNI (already on)
02-26 15:00:29.730: V/WebViewChromium(977): Binding Chromium to the background looperLooper{b1dceb80}
02-26 15:00:29.750: I/chromium(977): [INFO:library_loader_hooks.cc(112)] Chromium logging enabled: level = 0, default verbosity = 0
02-26 15:00:29.770: I/BrowserProcessMain(977): Initializing chromium process, renderers=0
02-26 15:00:29.960: E/chromium(977): [ERROR:gl_surface_egl.cc(153)] No suitable EGL configs found.
02-26 15:00:29.960: E/chromium(977): [ERROR:gl_surface_egl.cc(620)] GLSurfaceEGL::InitializeOneOff failed.
02-26 15:00:29.960: E/chromium(977): [ERROR:gl_surface_egl.cc(153)] No suitable EGL configs found.
02-26 15:00:29.960: E/chromium(977): [ERROR:gl_surface_egl.cc(620)] GLSurfaceEGL::InitializeOneOff failed.
02-26 15:00:29.970: E/chromium(977): [ERROR:gpu_info_collector.cc(86)] gfx::GLSurface::InitializeOneOff() failed
02-26 15:00:30.000: W/chromium(977): [WARNING:proxy_service.cc(888)] PAC support disabled because there is no system implementation
02-26 15:00:30.150: D/dalvikvm(977): GC_FOR_ALLOC freed 88K, 5% free 3235K/3392K, paused 48ms, total 50ms
02-26 15:00:30.160: I/dalvikvm-heap(977): Grow heap (frag case) to 4.297MB for 1127536-byte allocation
02-26 15:00:30.230: D/dalvikvm(977): GC_FOR_ALLOC freed 3K, 4% free 4333K/4496K, paused 67ms, total 67ms
02-26 15:00:30.800: D/gralloc_goldfish(977): Emulator without GPU emulation detected.
02-26 15:00:30.880: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:31.870: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:31.930: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:32.000: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:32.020: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:32.090: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:32.130: W/AwContents(977): nativeOnDraw failed; clearing to background color.
02-26 15:00:31.817: D/AndroidRuntime(977): Shutting down VM
02-26 15:00:31.817: W/dalvikvm(977): threadid=1: thread exiting with uncaught exception (group=0xb1af5b90)
02-26 15:00:31.827: E/AndroidRuntime(977): FATAL EXCEPTION: main
02-26 15:00:31.827: E/AndroidRuntime(977): Process: com.example.thelexapp, PID: 977
02-26 15:00:31.827: E/AndroidRuntime(977): java.lang.IllegalStateException: Could not execute method of the activity
02-26 15:00:31.827: E/AndroidRuntime(977): at android.view.View$1.onClick(View.java:3814)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.view.View.performClick(View.java:4424)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.view.View$PerformClick.run(View.java:18383)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.os.Handler.handleCallback(Handler.java:733)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.os.Handler.dispatchMessage(Handler.java:95)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.os.Looper.loop(Looper.java:137)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-26 15:00:31.827: E/AndroidRuntime(977): at java.lang.reflect.Method.invokeNative(Native Method)
02-26 15:00:31.827: E/AndroidRuntime(977): at java.lang.reflect.Method.invoke(Method.java:515)
02-26 15:00:31.827: E/AndroidRuntime(977): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-26 15:00:31.827: E/AndroidRuntime(977): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-26 15:00:31.827: E/AndroidRuntime(977): at dalvik.system.NativeStart.main(Native Method)
02-26 15:00:31.827: E/AndroidRuntime(977): Caused by: java.lang.reflect.InvocationTargetException
02-26 15:00:31.827: E/AndroidRuntime(977): at java.lang.reflect.Method.invokeNative(Native Method)
02-26 15:00:31.827: E/AndroidRuntime(977): at java.lang.reflect.Method.invoke(Method.java:515)
02-26 15:00:31.827: E/AndroidRuntime(977): at android.view.View$1.onClick(View.java:3809)
02-26 15:00:31.827: E/AndroidRuntime(977): ... 11 more
02-26 15:00:31.827: E/AndroidRuntime(977): Caused by: java.lang.NullPointerException
02-26 15:00:31.827: E/AndroidRuntime(977): at com.example.thelexapp.MainActivity.getPositionAndGetWheater(MainActivity.java:33)
02-26 15:00:31.827: E/AndroidRuntime(977): ... 14 more
02-26 15:00:37.167: I/Process(977): Sending signal. PID: 977 SIG: 9
Are you testing it on emulator or device? There is a posibility that your Location location is null. Please make sure you have corresponding permission in your manifest. To handle such situations, you should check your location for null:
public void getPositionAndGetWheater(View view) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String longitudestring = String.valueOf(longitude);
String latitudestring = String.valueOf(latitude);
String URLforweather = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=" + longitudestring + "," + latitudestring + "&format=xml&num_of_days=1&key=IHAVEAAPIKEYBUTI'MNOTPOSTINGITONTHEFORUMFORSECURITYREASONS";
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(URLforweather);
} else {
//show error
}
}

How to change textview over tabhost listener

I'm new android programmer, and I don't know how to set new text of TextView after call by OnTabChangeListener. I've tried a lot of ways but each time was displayed weird error.
Edit: (Lastest code)
MainActivity.java:
package com.RobsoN;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TabHost tabHost = getTabHost();
Log.i("App","App initialization");
TabSpec start = tabHost.newTabSpec("Start");
start.setIndicator("Start", getResources().getDrawable(android.R.drawable.ic_menu_rotate));
Intent photosIntent = new Intent(this, Start.class);
start.setContent(photosIntent);
TabSpec settings = tabHost.newTabSpec("Ustawienia");
settings.setIndicator("Ustawienia", getResources().getDrawable(android.R.drawable.ic_menu_manage));
Intent songsIntent = new Intent(this, Settings.class);
settings.setContent(songsIntent);
TabSpec info = tabHost.newTabSpec("Informacje");
info.setIndicator("Informacje", getResources().getDrawable(android.R.drawable.ic_menu_help));
Intent videosIntent = new Intent(this, Other.class);
info.setContent(videosIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(start);
tabHost.addTab(settings);
tabHost.addTab(info);
tabHost.setOnTabChangedListener(new OnTabChangeListener(){
public void onTabChanged(String tabId) {
if(tabId.equals("Informacje"))
{
Other child = (Other) getTabHost().getChildAt(0).getContext(); //Error here: 1 java.lang.ClassCastException: com.RobsoN.MainActivity 2 com.RobsoN.MainActivity$1.onTabChanged(MainActivity.java:50)
child.refreshInfo();
}
}});
}
}
Other.java:
package com.RobsoN;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Other extends Activity {
Button button_update;
TextView stat_lastestappversion;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_other);
stat_lastestappversion = (TextView) findViewById(R.id.stat_lastestappversion);
button_update = (Button) findViewById(R.id.button_update);
button_update.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
}
});
}
public void refreshInfo()
{
stat_lastestappversion = (TextView) findViewById(R.id.stat_lastestappversion);
stat_lastestappversion.setText("TEST TEST 321");
}
}
Error:
05-05 13:00:59.845: E/AndroidRuntime(314): FATAL EXCEPTION: main
05-05 13:00:59.845: E/AndroidRuntime(314): java.lang.ClassCastException: com.RobsoN.MainActivity
05-05 13:00:59.845: E/AndroidRuntime(314): at com.RobsoN.MainActivity$1.onTabChanged(MainActivity.java:50)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.widget.TabHost.invokeOnTabChangeListener(TabHost.java:356)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.widget.TabHost.setCurrentTab(TabHost.java:341)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:129)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:453)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.view.View.performClick(View.java:2408)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.view.View$PerformClick.run(View.java:8816)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.os.Handler.handleCallback(Handler.java:587)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.os.Handler.dispatchMessage(Handler.java:92)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.os.Looper.loop(Looper.java:123)
05-05 13:00:59.845: E/AndroidRuntime(314): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-05 13:00:59.845: E/AndroidRuntime(314): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 13:00:59.845: E/AndroidRuntime(314): at java.lang.reflect.Method.invoke(Method.java:521)
05-05 13:00:59.845: E/AndroidRuntime(314): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-05 13:00:59.845: E/AndroidRuntime(314): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-05 13:00:59.845: E/AndroidRuntime(314): at dalvik.system.NativeStart.main(Native Method)
as Luksprog says you can not use direct intialization of activity like you did in java. As far I can see you want to show a textview in a child activity of your tab host. To do so you can use the following
Other child = (Other) getTabHost().getChildAt(0).getContext();
child.refreshInfo();
N.B.
As you are new android programmer it is highly recommended to start with Fragments. Tab concept is depcrecated long time ago. Old programmers may still work on it to support their existing programs but as a new programmer you better avoid it.
UPDATE:
You can do another thing
getTabHost().setCurrentTab(tabindex);
Other child= (Other) this.getCurrentActivity();
child.refreshInfo();

Android.widget textView to android.widget.button

I am new to Android. I am trying to build this tiny app however every time I add the code in bold:
d = (Button) findViewById (R.id.tvDis);
the app crashes and if I remove this line, everything works fine. I am runing this on android 2.2 api 8 version and nexus s emulator.
package com.maximusstudios.numtowords;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
/**Called when the activity is first created.*/
int counter;
Button add, sub;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
**d = (Button) findViewById (R.id.tvDis);**
sub = (Button) findViewById(R.id.bSub);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Your Total is 0"
android:textSize="20dp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDis"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bAdd"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bSub"
/>
</LinearLayout>
Error list:
02-10 18:00:21.452: D/AndroidRuntime(910): Shutting down VM
02-10 18:00:21.452: W/dalvikvm(910): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-10 18:00:21.472: E/AndroidRuntime(910): FATAL EXCEPTION: main
02-10 18:00:21.472: E/AndroidRuntime(910): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maximusstudios.numtowords/com.maximusstudios.numtowords.MainActivity}: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Handler.dispatchMessage(Handler.java:99)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Looper.loop(Looper.java:123)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invoke(Method.java:521)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-10 18:00:21.472: E/AndroidRuntime(910): at dalvik.system.NativeStart.main(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): Caused by: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at com.maximusstudios.numtowords.MainActivity.onCreate(MainActivity.java:23)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-10 18:00:21.472: E/AndroidRuntime(910): ... 11 more
Change to
d = (TextView) findViewById (R.id.tvDis);
Your casting was wrong. With your code, when you do (Button), you are trying to cast the TextView that is returned by findViewById() into a Button, which doesn't work due to them being incompatible types.
You define d as a TextView and try to cast it to a Button
Should be
d = (TextView) findViewById (R.id.tvDis);
The error you're getting is a ClassCastException

How to print my file?

Hi how to print file list...now I trying to print my file list...but I am its not printing...please help me....
This is my coding:
package ImageViewExample.ImageViewExample;
import java.io.File;
import java.util.ArrayList;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
//import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class ImageViewExample extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
img, null,null,
MediaStore.Images.Thumbnails.IMAGE_ID + "");
System.out.println("cursor"+managedQuery(MediaStore.Images
.Thumbnails.EXTERNAL_CONTENT_URI, img, null,null,
MediaStore.Images.Thumbnails.IMAGE_ID + ""));
image_column_index =
imagecursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
System.out.println("index"+imagecursor.getColumnIndexOrThrow(MediaStore
.Images.Thumbnails._ID));
count = imagecursor.getCount();
System.out.println("image"+count);
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImAdapterh(this));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,int position, long id)
{
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
proj,null, null, null);
// System.out.println("doubt"+managedQuery(MediaStore
.Images.Media.EXTERNAL_CONTENT_URI, proj,null, null, null));
actual_image_column_index =
actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImAdapterh extends BaseAdapter{
File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
int count=dir.list().length;
String[] fileNames = dir.list();
private Context mContext;
public ImAdapterh(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
for(String bitmapFileName : fileNames)
{
if (convertView == null)
{ // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new Gallery.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" +
bitmapFileName);
imageView.setImageBitmap(bmp);
}else
{
imageView = (ImageView) convertView;
}
} return imageView;
}
}}
I wish to print my file list:
File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
int count=dir.list().length;
String[] fileNames = dir.list();
logcat error:
05-05 22:39:42.147: DEBUG/dalvikvm(739): GC_EXTERNAL_ALLOC freed 1035 objects / 68800
bytes in 141ms
05-05 22:39:42.497: DEBUG/dalvikvm(739): GC_EXTERNAL_ALLOC freed 418 objects / 217344
bytes in 118ms
05-05 22:39:42.568: DEBUG/AndroidRuntime(739): Shutting down VM
05-05 22:39:42.578: WARN/dalvikvm(739): threadid=1: thread exiting with uncaught
exception (group=0x4001d800)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): FATAL EXCEPTION: main
05-05 22:39:42.608: ERROR/AndroidRuntime(739): java.lang.ClassCastException:
android.widget.Gallery$LayoutParams
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.GridView.onMeasure(GridView.java:934)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.View.measure(View.java:8171)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.View.measure(View.java:8171)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.View.measure(View.java:8171)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.View.measure(View.java:8171)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.View.measure(View.java:8171)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.ViewRoot.performTraversals(ViewRoot.java:801)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.os.Handler.dispatchMessage(Handler.java:99)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.os.Looper.loop(Looper.java:123)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
android.app.ActivityThread.main(ActivityThread.java:4627)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
java.lang.reflect.Method.invokeNative(Native Method)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
java.lang.reflect.Method.invoke(Method.java:521)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-05 22:39:42.608: ERROR/AndroidRuntime(739): at
dalvik.system.NativeStart.main(Native Method)
05-05 22:39:42.638: WARN/ActivityManager(64): Force finishing activity
ImageViewExample.ImageViewExample/.ImageViewExample
05-05 22:39:43.157: WARN/ActivityManager(64): Activity pause timeout for
HistoryRecord{43fb0c88 ImageViewExample.ImageViewExample/.ImageViewExample}
This will print your files to the logcat, but note that this code has to be located in some method, not just in the class.
for (String fName : fileNames)
{
Log.i("MYAPPTAG", fName);
}

Categories