CalendarView in Dialog - java

i would like to display a CalendarView in a dialog , at the center of the screen.
Why in the dialog ? Because when i open my CalendarView , it's take all the screen , whereas i would like to display it , in dialog to see the background..
So it's my calendar_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" >
<CalendarView
android:id="#+id/calendarView1"
android:layout_width="400dp"
android:layout_height="400dp"
android:layout_marginLeft="150dp"/>
</RelativeLayout>
and it's my method who open my calendar
public void showCalendar() {
Dialog dialog = new Dialog(getBaseContext());
// setContentView(R.layout.calendar_main);
cal = (CalendarView) findViewById(R.id.calendarView1);
dialog.setContentView(R.layout.calendar_main);
cal.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Selected Date is\n\n"
+dayOfMonth+" : "+month+" : "+year ,
Toast.LENGTH_LONG).show();
}
});
}
Without Dialog , my calendar open correctly with the good size that i defined in xml. but with dialog, my app crash..
It's my error log :
E/AndroidRuntime(27862): FATAL EXCEPTION: main
E/AndroidRuntime(27862): java.lang.NullPointerException
E/AndroidRuntime(27862): at com.pdf.GetViewPDF.showCalendar(GetViewPDF.java:90)
E/AndroidRuntime(27862): at com.pdf.GetViewPDF.onOptionsItemSelected(GetViewPDF.java:113)
E/AndroidRuntime(27862): at android.app.Activity.onMenuItemSelected(Activity.java:2453)
E/AndroidRuntime(27862): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:846)
E/AndroidRuntime(27862): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
E/AndroidRuntime(27862): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:956)
E/AndroidRuntime(27862): at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:170)
E/AndroidRuntime(27862): at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:85)
E/AndroidRuntime(27862): at android.view.View.performClick(View.java:3117)
E/AndroidRuntime(27862): at android.view.View$PerformClick.run(View.java:11941)
E/AndroidRuntime(27862): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(27862): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(27862): at android.os.Looper.loop(Looper.java:132)
E/AndroidRuntime(27862): at android.app.ActivityThread.main(ActivityThread.java:4123)
E/AndroidRuntime(27862): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27862): at java.lang.reflect.Method.invoke(Method.java:491)
E/AndroidRuntime(27862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
E/AndroidRuntime(27862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
E/AndroidRuntime(27862): at dalvik.system.NativeStart.main(Native Method)
Otherwise , i call showCalendar from a item buton in my ActionBar
and the NullPointerException appear when i call my listener :
cal.setOnDateChangeListener(new OnDateChangeListener() {...

Try to change this:
cal = (CalendarView) findViewById(R.id.calendarView1);
dialog.setContentView(R.layout.calendar_main);
to this:
dialog.setContentView(R.layout.calendar_main);
cal = (CalendarView) dialog.findViewById(R.id.calendarView1);

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]);
}
});
}

ADT simple app - fatal exception [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I have just started out with Android and Java, and i have just made a simple app with a couple of textviews, a button and a edittext.
When i run the app i get an error saying the: Unfortunately, FirstApp has stopped.
I am familiar with programming, and wonder if i miss some library, or if ADT is misconfigured.
I have tried to clean and rebuild, to right click the project in the Package explorer and Android Tools -> Add support library, restarted the emulator, restarted ADT and restarted the computer. Cant figure out what does this.
Can any of you see something wrong here?
MainActivity.java imports
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.os.Build;
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCalc = (Button)findViewById(R.id.btnCalc);
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText number = (EditText)findViewById(R.id.num);
TextView display = (TextView)findViewById(R.id.display);
double num = Double.parseDouble(number.getText().toString());
num = num * 5;
display.setText(num + "");
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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;
}
fragment_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="com.danlevi.testproject.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/lblTitle" />
<EditText
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/num"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="#string/btnCalc" />
<TextView
android:id="#+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/btnCalc"
android:layout_marginTop="16dp" />
</RelativeLayout>
Console
[2014-05-16 18:33:16 - TestProject] Dx
trouble writing output: already prepared
[2014-05-16 18:33:17 - TestProject] ------------------------------
[2014-05-16 18:33:17 - TestProject] Android Launch!
[2014-05-16 18:33:17 - TestProject] adb is running normally.
[2014-05-16 18:33:17 - TestProject] Performing com.danlevi.testproject.MainActivity activity launch
[2014-05-16 18:33:17 - TestProject] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'Android'
[2014-05-16 18:33:17 - TestProject] Uploading TestProject.apk onto device 'emulator-5554'
[2014-05-16 18:33:18 - TestProject] Installing TestProject.apk...
[2014-05-16 18:33:30 - TestProject] Success!
[2014-05-16 18:33:30 - TestProject] Starting activity com.danlevi.testproject.MainActivity on device emulator-5554
[2014-05-16 18:33:33 - TestProject] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.danlevi.testproject/.MainActivity }
LogCat
05-16 12:33:37.412: D/AndroidRuntime(1579): Shutting down VM
05-16 12:33:37.412: W/dalvikvm(1579): threadid=1: thread exiting with uncaught exception (group=0xb2b08ba8)
05-16 12:33:37.432: E/AndroidRuntime(1579): FATAL EXCEPTION: main
05-16 12:33:37.432: E/AndroidRuntime(1579): Process: com.danlevi.testproject, PID: 1579
05-16 12:33:37.432: E/AndroidRuntime(1579): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.danlevi.testproject/com.danlevi.testproject.MainActivity}: java.lang.NullPointerException
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.os.Handler.dispatchMessage(Handler.java:102)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.os.Looper.loop(Looper.java:136)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-16 12:33:37.432: E/AndroidRuntime(1579): at java.lang.reflect.Method.invokeNative(Native Method)
05-16 12:33:37.432: E/AndroidRuntime(1579): at java.lang.reflect.Method.invoke(Method.java:515)
05-16 12:33:37.432: E/AndroidRuntime(1579): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-16 12:33:37.432: E/AndroidRuntime(1579): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-16 12:33:37.432: E/AndroidRuntime(1579): at dalvik.system.NativeStart.main(Native Method)
05-16 12:33:37.432: E/AndroidRuntime(1579): Caused by: java.lang.NullPointerException
05-16 12:33:37.432: E/AndroidRuntime(1579): at com.danlevi.testproject.MainActivity.onCreate(MainActivity.java:25)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.Activity.performCreate(Activity.java:5231)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-16 12:33:37.432: E/AndroidRuntime(1579): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-16 12:33:37.432: E/AndroidRuntime(1579): ... 11 more
05-16 12:33:44.352: I/Process(1579): Sending signal. PID: 1579 SIG: 9
This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.
Move that piece of code in the onCreateView() method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
In your code, move
changer = (Button) findViewById(R.id.change1);
changeme = (TextView) findViewById (R.id.changeme1);
changer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
changeme.setText("Changed");
}
});
to onCreateView() method of the fragment

how to make my background to flash constantly with animation

My code is as below but.. when i ran it, it doesn't do anything
Animation animation = new AlphaAnimation(1, 0); // Change alpha
// from fully
// visible to
// invisible
animation.setDuration(500); // duration - half a second
animation.setInterpolator(new LinearInterpolator()); // do not alter
// animation
// rate
animation.setRepeatCount(Animation.INFINITE); // Repeat animation
// infinitely
animation.setRepeatMode(Animation.REVERSE); // Reverse animation at
// the
// end so the layout will
// fade back in
LinearLayout x = (LinearLayout)findViewById(R.id.warning);
x.clearAnimation();
logcat after vipul mittal suggest
12-11 20:08:18.477: E/AndroidRuntime(1571): FATAL EXCEPTION: main
12-11 20:08:18.477: E/AndroidRuntime(1571): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.NTS.standroid/com.NTS.standroid.Settings}: java.lang.NullPointerException
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.os.Handler.dispatchMessage(Handler.java:99)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.os.Looper.loop(Looper.java:130)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-11 20:08:18.477: E/AndroidRuntime(1571): at java.lang.reflect.Method.invokeNative(Native Method)
12-11 20:08:18.477: E/AndroidRuntime(1571): at java.lang.reflect.Method.invoke(Method.java:507)
12-11 20:08:18.477: E/AndroidRuntime(1571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-11 20:08:18.477: E/AndroidRuntime(1571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-11 20:08:18.477: E/AndroidRuntime(1571): at dalvik.system.NativeStart.main(Native Method)
12-11 20:08:18.477: E/AndroidRuntime(1571): Caused by: java.lang.NullPointerException
12-11 20:08:18.477: E/AndroidRuntime(1571): at com.NTS.standroid.Settings.onCreate(Settings.java:35)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-11 20:08:18.477: E/AndroidRuntime(1571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-11 20:08:18.477: E/AndroidRuntime(1571): ... 11 more
any suggestions please.
I want to make my background to constantly flash after i hit a button
My current code
}
#SuppressLint("NewApi")
public void tintBackground() {
LinearLayout x = (LinearLayout)findViewById(R.id.warning);
ColorDrawable[] color = { new ColorDrawable(Color.RED),
new ColorDrawable(Color.WHITE) };
TransitionDrawable trans = new TransitionDrawable(color);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
x.setBackgroundDrawable(trans);
} else {
x.setBackground(trans);
}
trans.startTransition(2000); // do transition over 2 seconds
}
and xml file
<?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"
android:layout="#+id/warning">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="#+id/warning1"
android:layout_marginTop="50dp"
android:layout_marginLeft="100dp"
android:background="#drawable/warning"
/>
</LinearLayout>
I use the following code to tint the background of my app, maybe you can use that repeatedly:
#SuppressLint("NewApi")
public void tintBackground() {
View rootView = findViewById(android.R.id.content);
ColorDrawable[] color = { new ColorDrawable(Color.RED),
new ColorDrawable(Color.WHITE) };
TransitionDrawable trans = new TransitionDrawable(color);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
rootView.setBackgroundDrawable(trans);
} else {
rootView.setBackground(trans);
}
trans.startTransition(2000); // do transition over 2 seconds
}
You must start animation on the linearlayout:
Animation animation = new AlphaAnimation(1, 0); // Change alpha
// from fully
// visible to
// invisible
animation.setDuration(500); // duration - half a second
animation.setInterpolator(new LinearInterpolator()); // do not alter
// animation
// rate
animation.setRepeatCount(Animation.INFINITE); // Repeat animation
// infinitely
animation.setRepeatMode(Animation.REVERSE); // Reverse animation at
// the
// end so the layout will
// fade back in
LinearLayout x = (LinearLayout)findViewById(R.id.warning);
x.startAnimation(animation)//<-- start animation don't clear it
I have used this to make a View fade in and out repeatedly:
fadeIn = new AlphaAnimation(0.25f, 1);
fadeIn.setInterpolator(new AccelerateInterpolator()); // add this
fadeIn.setDuration(500);
fadeIn.setFillAfter(true);
fadeIn.setAnimationListener(new RepeatAnimationListener());
fadeOut = new AlphaAnimation(1, 0.25f);
fadeOut.setInterpolator(new DecelerateInterpolator()); // and this
fadeOut.setDuration(500);
fadeOut.setFillAfter(true);
fadeOut.setAnimationListener(new RepeatAnimationListener());
private boolean currently_fadeOut;
private class RepeatAnimationListener implements AnimationListener {
public void onAnimationEnd(Animation animation) {
if (currently_fadeOut) {
view.startAnimation(fadeIn);
currently_fadeOut = false;
} else {
view.startAnimation(fadeOut);
currently_fadeOut = true;
}
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
}
}
// automatically repeated because of RepeatAnimationListener
view.startAnimation(fadeOut);

Parse JSON to TextViews

So im parsing JSON data from a API Enabled website, It requires authentiucation by a APIKEY, My issue is that im trying to parse the data then insert it into TextViews on the UI. My current code previously used to use a HashMap and a ListView However now im trying to change it to just populate the data into the TextViews. Currently, I've started changing the code over and now im getting RunTimeExceptions with my current code. Any Help would be greatly appreciated.
Issue Resolved
public class ParseMoreDetails extends Activity {
private Context context;
private static String url = "https://api.company.com/api/systems?";
private static final String TAG_SYSTEM = "systems";
private static final String TAG_SYSTEM_ID = "system_id";
private static final String TAG_CITY = "city";
private static final String TAG_STATE = "state";
private static final String TAG_SYSTEM_NAME = "system_name";
private static final String TAG_SYSTEM_PUBLIC_NAME = "system_public_name";
private static final String TAG_STATUS = "status";
TextView textView;
TextView textView2;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView2);
textView2 = (TextView) findViewById(R.id.TextView01);
textView3 = (TextView) findViewById(R.id.TextView03);
new ProgressTask(ParseMoreDetails.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, ArrayList<String>> {
private ProgressDialog dialog;
ArrayList<String> arrfortextviews;
private ParseMoreDetails activity;
// private List<Message> messages;
public ProgressTask(ParseMoreDetails parseMoreDetails) {
this.activity = parseMoreDetails;
context = parseMoreDetails;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(ArrayList<String> success) {
if(arrfortextviews.size() >0){
textView.setText(success.get(0));
textView2.setText(success.get(1));
textView3.setText(success.get(2));
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected ArrayList<String> doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
arrfortextviews=new ArrayList<String>();
// Using APIKEY from strings.xml
String apikey = getString(R.string.apikey);
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vcolor = c.getString(TAG_SYSTEM_ID);
String vfuel = c.getString(TAG_CITY);
String vtread = c.getString(TAG_STATE);
arrfortextviews.add(vcolor);
arrfortextviews.add(vfuel);
arrfortextviews.add(vtread);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return arrfortextviews;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="System ID: " />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City:" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.00" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="State:" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..." />
</LinearLayout>
</FrameLayout>
</LinearLayout>
Current Errors
RuntimeException - NullPointerException
Leaked Window com.android.internal.policy.impl.PhoneWindow$DecorView
LogCat - UPDATED
05-01 10:27:47.040: E/AndroidRuntime(28236): FATAL EXCEPTION: AsyncTask #1
05-01 10:27:47.040: E/AndroidRuntime(28236): java.lang.RuntimeException: An error occured while executing doInBackground()
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.lang.Thread.run(Thread.java:856)
05-01 10:27:47.040: E/AndroidRuntime(28236): Caused by: java.lang.NullPointerException
05-01 10:27:47.040: E/AndroidRuntime(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.doInBackground(ParseMoreDetails.java:116)
05-01 10:27:47.040: E/AndroidRuntime(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.doInBackground(ParseMoreDetails.java:1)
05-01 10:27:47.040: E/AndroidRuntime(28236): at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-01 10:27:47.040: E/AndroidRuntime(28236): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-01 10:27:47.040: E/AndroidRuntime(28236): ... 5 more
05-01 10:27:55.035: I/Choreographer(28236): Skipped 464 frames! The application may be doing too much work on its main thread.
05-01 10:27:55.210: E/WindowManager(28236): Activity com.jitesh.androidjsonparser.ParseMoreDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4285c818 that was originally added here
05-01 10:27:55.210: E/WindowManager(28236): android.view.WindowLeaked: Activity com.jitesh.androidjsonparser.ParseMoreDetails has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4285c818 that was originally added here
05-01 10:27:55.210: E/WindowManager(28236): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:402)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
05-01 10:27:55.210: E/WindowManager(28236): at android.view.Window$LocalWindowManager.addView(Window.java:554)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Dialog.show(Dialog.java:277)
05-01 10:27:55.210: E/WindowManager(28236): at com.jitesh.androidjsonparser.ParseMoreDetails$ProgressTask.onPreExecute(ParseMoreDetails.java:86)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.AsyncTask.execute(AsyncTask.java:534)
05-01 10:27:55.210: E/WindowManager(28236): at com.jitesh.androidjsonparser.ParseMoreDetails.onCreate(ParseMoreDetails.java:63)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Activity.performCreate(Activity.java:5206)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.access$600(ActivityThread.java:140)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 10:27:55.210: E/WindowManager(28236): at android.os.Looper.loop(Looper.java:137)
05-01 10:27:55.210: E/WindowManager(28236): at android.app.ActivityThread.main(ActivityThread.java:4898)
05-01 10:27:55.210: E/WindowManager(28236): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 10:27:55.210: E/WindowManager(28236): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 10:27:55.210: E/WindowManager(28236): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
05-01 10:27:55.210: E/WindowManager(28236): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
05-01 10:27:55.210: E/WindowManager(28236): at dalvik.system.NativeStart.main(Native Method)
In Here :
TextView textView = (TextView) findViewById(R.id.textView2); //<<< here
TextView textView2 = (TextView) findViewById(R.id.TextView01);//<<< here
TextView textView3 = (TextView) findViewById(R.id.TextView03);//<<< here
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
you are using findViewById before setting layout for current Activity .so you will need to move all Widgets initialize inside onCreate method of Activity after setting layout for it. Change your code as:
TextView textView,textView2,textView3; //<<<declare here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize all textViews here
textView = (TextView) findViewById(R.id.textView2);
textView2 = (TextView) findViewById(R.id.TextView01);
textView3 = (TextView) findViewById(R.id.TextView03);
......
you are having an error in doInBackround of the AsyncTask
I suspect that
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);
returns null
put this line instead may be it will work
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url + "key=" + apikey);
you shouldn't handle UI elements (TextViews) from doInBackground OnPostExecute is made for that

Unfortunately app has stopped working

I am new to android application development. I was doing this tutorial app.It's a very simple one. It adds one and subtracts one from the counter.When I run it in the emulator ,it says "Unfortunately tutorial has stopped working." There are no errors in the code. The API level is 17. Please help me out.
Code for java:
public class Startingpoint extends Activity {
int counter=0;
Button add,subtract;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startingpoint);
add = (Button) findViewById(R.id.bAdd);
subtract= (Button) findViewById(R.id.bSubtract);
display= (Button) findViewById(R.id.text);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("The total is " + counter);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("The total is " + counter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startingpoint, menu);
return true;
}
}
Layout code in xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your total is 0"
android:textSize="35dp"
android:layout_gravity="center"
android:gravity="center"/>
<Button android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Add One"
android:layout_gravity="center"
android:textSize="25dp"
android:id="#+id/bAdd"/>
<Button android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Subtract One"
android:layout_gravity="center"
android:textSize="25dp"
android:id="#+id/bSubtract"/>
</LinearLayout>
Here is the logcat :
03-02 02:45:10.730: D/AndroidRuntime(780): Shutting down VM
03-02 02:45:10.730: W/dalvikvm(780): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-02 02:45:10.750: E/AndroidRuntime(780): FATAL EXCEPTION: main
03-02 02:45:10.750: E/AndroidRuntime(780): java.lang.RuntimeException: Unable to start activity ComponentInfo{tutorial.example.tutorial/tutorial.example.tutorial.Startingpoint}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.os.Looper.loop(Looper.java:137)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-02 02:45:10.750: E/AndroidRuntime(780): at java.lang.reflect.Method.invokeNative(Native Method)
03-02 02:45:10.750: E/AndroidRuntime(780): at java.lang.reflect.Method.invoke(Method.java:511)
03-02 02:45:10.750: E/AndroidRuntime(780): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-02 02:45:10.750: E/AndroidRuntime(780): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-02 02:45:10.750: E/AndroidRuntime(780): at dalvik.system.NativeStart.main(Native Method)
03-02 02:45:10.750: E/AndroidRuntime(780): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
03-02 02:45:10.750: E/AndroidRuntime(780): at tutorial.example.tutorial.Startingpoint.onCreate(Startingpoint.java:22)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.Activity.performCreate(Activity.java:5104)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-02 02:45:10.750: E/AndroidRuntime(780): ... 11 more
display= (Button) findViewById(R.id.text);
should be
display= (TextView) findViewById(R.id.text);
Since display is supposed to reference a TextView instance, but you're explictly casting into a Button, and these are not compatible types.
As you got the answer from A-C this time, but for next time in android application development a important suggestion:
Always see the logcat for error, and see the "Caused by:" tag, It specifies what was the cause of the problem with sufficient detail, Also see the line no that caused that error.
And try to find what can be wrong with that line of code.
For example: in your logcat it is showing-
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
at tutorial.example.tutorial.Startingpoint.onCreate(Startingpoint.java:22)
So you can try to read the log, and you will understand that in your file Startingpoint.java at line 22 which is located in onCreate method the error is android.widget.TextView cannot be cast to android.widget.Button. So you can easily remove your errors without any help.
Hope that helps not only you current problem but prevented your future time and efforts.

Categories