I am learning android programming using eclipse. I coded a twitter app that simply let's you tweet a status and view a user's timeline. However when I try run the app on my samsung galaxy tab 3.0 the app starts up, all i see is the title at the top, none of the textviews or buttons show up then after 2 seconds the screen goes black and i get the error message ("Unfortunately TwitterApp has stopped") I cant imagine it's something to do with twitter since none of the widgets are being displayed. Here is the code from my main activity, and the activity_main.xml file. And the logCat. Ill even include the manifest
package com.example.twitterapp;
import java.util.List;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView countCharsTV, timelineTV;
EditText usernameET, tweetET;
Button tweetBTN, timelineBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countCharsTV = (TextView) findViewById(R.id.textView1);
timelineTV = (TextView) findViewById(R.id.textView2);
timelineTV.setMovementMethod(new ScrollingMovementMethod());
tweetET = (EditText) findViewById(R.id.editText1);
tweetET.addTextChangedListener(new MyTextWatcher());
usernameET = (EditText) findViewById(R.id.editText2);
tweetBTN = (Button) findViewById(R.id.button1);
tweetBTN.setOnClickListener(tweetBTNOnClickListener);
timelineBTN.setOnClickListener(timelineBTNOnClickListener);
}
//BUTTON CLICK LISTENERS WITHOUT IMPLEMENTS
public OnClickListener tweetBTNOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
new MyAsyncTaskTweet().execute(tweetET.getText().toString());
}
};
public OnClickListener timelineBTNOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTaskTimeline().execute(timelineTV.getText().toString());
}
};
//END OF BUTTON CLICK LISTENERS
//COUNT CHARS IN TEXTVIEW USING IMPLEMENTS
class MyTextWatcher implements TextWatcher {
#Override
public void afterTextChanged(Editable arg0) {
countCharsTV.setText("" + tweetET.getText().length());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
}
//End OF COUNT CHARS IN TEXTVIEW
//ASYNC TASK CLASSES
//TWEET ASYNC TASK
public class MyAsyncTaskTweet extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... tweet) {
String result = "";
Twitter twitter = TwitterFactory.getSingleton();
try{
twitter.updateStatus(tweet[0]);
result = "Success";
}catch(TwitterException twitterException) {
result = "Failed to update status";
}
return result;
}
#Override
protected void onPostExecute(String result){
tweetET.setHint(result);
tweetET.setText("");
}
}
//END OF TWEET ASYNC TASK
public class MyAsyncTaskTimeline extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... username) {
String result = new String("");
List<twitter4j.Status> statuses = null;
Twitter twitter = TwitterFactory.getSingleton();
try {
statuses = twitter.getUserTimeline(username[0]);
}catch (TwitterException twitterException) {
twitterException.printStackTrace();
}
for(twitter4j.Status status : statuses) {
result += status.getText();
result += "\n";
}
return result;
}
#Override
protected void onPostExecute(String result) {
usernameET.setText("");
timelineTV.setText(result);
}
}
#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;
}
}
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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:text="Tweet" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="Type your tweet here" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText2"
android:layout_alignBottom="#+id/editText2"
android:layout_toLeftOf="#+id/editText2"
android:text="'#" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_toRightOf="#+id/textView1"
android:text="Timeline" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:ems="10"
android:hint="Type a username here" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button2"
android:layout_toRightOf="#+id/button1"
android:text="Timeline will go here" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.twitterapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
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.twitterapp.MainActivity"
android:label="#string/app_name" >
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat
03-21 22:46:25.117: W/ActivityThread(3806): Application com.example.twitterapp can be
debugged on port 8100...
03-21 22:46:25.289: E/SensorManager(3806): thread start
03-21 22:46:25.296: D/SensorManager(3806): registerListener :: handle = 1598182229
name= BOSCH BMC150 Acceleration Sensor delay= 200000
03-21 22:46:25.296: D/AndroidRuntime(3806): Shutting down VM
03-21 22:46:25.296: W/dalvikvm(3806): threadid=1: thread exiting with uncaught exception
(group=0x40dcd2a0)
03-21 22:46:25.304: E/AndroidRuntime(3806): FATAL EXCEPTION: main
03-21 22:46:25.304: E/AndroidRuntime(3806): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.example.twitterapp/com.example.twitterapp.MainActivity}:
java.lang.NullPointerException
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2129)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.access$700(ActivityThread.java:146)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.os.Handler.dispatchMessage(Handler.java:99)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.os.Looper.loop(Looper.java:137)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.main(ActivityThread.java:4949)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
java.lang.reflect.Method.invokeNative(Native Method)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
java.lang.reflect.Method.invoke(Method.java:511)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
dalvik.system.NativeStart.main(Native Method)
03-21 22:46:25.304: E/AndroidRuntime(3806): Caused by: java.lang.NullPointerException
03-21 22:46:25.304: E/AndroidRuntime(3806): at
com.example.twitterapp.MainActivity.onCreate(MainActivity.java:45)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.Activity.performCreate(Activity.java:5185)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
03-21 22:46:25.304: E/AndroidRuntime(3806): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
03-21 22:46:25.304: E/AndroidRuntime(3806): ... 11 more
03-21 22:46:38.398: I/Process(3806): Sending signal. PID: 3806 SIG: 9
Where is timelineBTN reference? "timelineBTN" was null.
timelineBTN = (Button)findViewById(R.id.);
Related
Here's the code of my main activty:
package com.manparvesh.Soil;
import com.manparvesh.soilclassification.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class myMainScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.classificationsystems);
Button aashtob = (Button) findViewById(R.id.aashto);
aashtob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1){
startActivity(new Intent(getApplicationContext(),AASHTO_Open.class));
}
});
Button uscsb = (Button) findViewById(R.id.uscs);
uscsb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),USCS_Open.class));
}
});
Button usdab = (Button) findViewById(R.id.usda);
usdab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v3) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),USDA_Open.class));
}
});
}
}
Here's the code of the class that I am trying to open:
package com.manparvesh.Soil;
import com.manparvesh.soilclassification.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.*;
public class AASHTO_Open extends Activity {
Button classify1,clear1,menu1;
EditText S10,S40,S200,ll,pi;
TextView CC,CdCd;
int c;
String C,Cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.aashto);
classify1=(Button)findViewById(R.id.classify1);
clear1=(Button)findViewById(R.id.clear1);
menu1=(Button)findViewById(R.id.menu1);
S10 = (EditText)findViewById(R.id.T11);
S40 = (EditText)findViewById(R.id.T12);
S200 = (EditText)findViewById(R.id.T13);
ll = (EditText)findViewById(R.id.T14);
pi = (EditText)findViewById(R.id.T15);
int s10 = Integer.parseInt(S10.getText().toString());
int s40 = Integer.parseInt(S40.getText().toString());
int s200 = Integer.parseInt(S200.getText().toString());
int LL = Integer.parseInt(ll.getText().toString());
int PI = Integer.parseInt(pi.getText().toString());
if (s10<=50){
if (s40<=30){
if (s200<=15 && PI<=6){
c=1;
}
}else if(s40<=50){
if (s200<=25){
c=2;
}
}else{
if (s200<=10){
c=3;
}else if (s200<=35){
if (LL<=40){
if (PI<=10){
c=4;
}else{
c=5;
}
}else{
if (PI<=10){
c=6;
}else{
c=7;
}
}
}else{
if (LL<=40){
if (PI<=10){
c=8;
}else{
c=9;
}
}else{
if (PI<=10){
c=10;
}else{
c=11;
}
}
}
}
}
if (("".equals(S10))|| ("".equals(S200)) || ("".equals(S40)) || ("".equals(LL)) || ("".equals(PI))){
throw new NumberFormatException();
}
switch(c){
case 1:
C="A-1-a";
Cd="stone fragments, gravel and sand";
break;
case 2:
C="A-1-b";
Cd="stone fragments, gravel and sand";
break;
case 3:
C="A-3";
Cd="fine sand";
break;
case 4:
C="A-2-4";
Cd="silty or clayey gravel and sand";
break;
case 5:
C="A-2-6";
Cd="silty or clayey gravel and sand";
break;
case 6:
C="A-2-5";
Cd="silty or clayey gravel and sand";
break;
case 7:
C="A-2-7";
Cd="silty or clayey gravel and sand";
break;
case 8:
C="A-4";
Cd="silty soils";
break;
case 9:
C="A-6";
Cd="clayey soils";
break;
case 10:
C="A-5";
Cd="silty soils";
break;
case 11:
C="A-7";
Cd="clayey soils";
break;
}
classify1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
CC.setText(C);
CdCd.setText(Cd);
}
});
menu1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
startActivity(new Intent("com.tutorial.CLEARSCREEN"));
}
});
clear1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
S10.setText("");
S40.setText("");
S200.setText("");
ll.setText("");
pi.setText("");
CC.setText("");
CdCd.setText("");
}
});
}
}`
The XML file of the layout I'm trying to open:
<?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:background="#drawable/bg3"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="105dp"
android:textColor="#FFFFFF"
android:text="AASHTO"
android:textSize="55dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:textColor="#FFFFFF"
android:id="#+id/textView2"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="Sieve no.10 (% passing)" />
<EditText
android:inputType="phone"
android:id="#+id/T11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:background="#99FFFFFF">
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:textColor="#FFFFFF"
android:id="#+id/textView4"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="Sieve no.40 (% passing)" />
<EditText
android:inputType="phone"
android:background="#99FFFFFF"
android:id="#+id/T12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:textColor="#FFFFFF"
android:id="#+id/aegg"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="Sieve no.200 (% passing)" />
<EditText
android:inputType="phone"
android:background="#99FFFFFF"
android:id="#+id/T13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:textColor="#FFFFFF"
android:id="#+id/textView6"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="Liquid Limit" />
<EditText
android:inputType="phone"
android:background="#99FFFFFF"
android:id="#+id/T14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:textColor="#FFFFFF"
android:id="#+id/textView3"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="Plasticity Index (=LL-PL)" />
<EditText
android:inputType="phone"
android:background="#99FFFFFF"
android:id="#+id/T15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="5dp">
<Button
android:textColor="#FFFFFF"
android:id="#+id/menu1"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:text="Menu"
android:gravity="center"
android:layout_marginRight="0.75dp"
android:background="#drawable/button_wood"
/>
<Button
android:textColor="#FFFFFF"
android:id="#+id/clear1"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:text="Clear"
android:layout_marginRight="0.75dp"
android:gravity="center"
android:background="#drawable/button_wood"
/>
<Button
android:textColor="#FFFFFF"
android:id="#+id/classify1"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:text="Classify"
android:gravity="center"
android:background="#drawable/button_wood"
/>
</LinearLayout>
</LinearLayout>
The Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.manparvesh.soilclassification"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19"
android:maxSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.manparvesh.Soil.MainActivity"
android:label="#layout/splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.manparvesh.Soil.myMainScreen" android:screenOrientation="portrait" android:theme="#style/AppTheme" android:label="#layout/classificationsystems"></activity>
<activity android:name="com.manparvesh.Soil.AASHTO_Open" android:theme="#style/AppTheme" android:description="#layout/aashto"></activity>
<activity android:name="com.manparvesh.Soil.USCS_Open" android:label="#layout/uscs"></activity>
<activity android:name="com.manparvesh.Soil.USDA_Open" android:theme="#style/AppTheme" android:label="#layout/usda"></activity>
</application>
</manifest>
Here's what the LogCat shows:
07-09 18:27:15.803: E/AndroidRuntime(686): FATAL EXCEPTION: main
07-09 18:27:15.803: E/AndroidRuntime(686): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.manparvesh.soilclassification/com.manparvesh.Soil.USCS_Open}: java.lang.NumberFormatException: Invalid double: ""
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread.access$600(ActivityThread.java:130)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.os.Looper.loop(Looper.java:137)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-09 18:27:15.803: E/AndroidRuntime(686): at java.lang.reflect.Method.invokeNative(Native Method)
07-09 18:27:15.803: E/AndroidRuntime(686): at java.lang.reflect.Method.invoke(Method.java:511)
07-09 18:27:15.803: E/AndroidRuntime(686): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-09 18:27:15.803: E/AndroidRuntime(686): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-09 18:27:15.803: E/AndroidRuntime(686): at dalvik.system.NativeStart.main(Native Method)
07-09 18:27:15.803: E/AndroidRuntime(686): Caused by: java.lang.NumberFormatException: Invalid double: ""
07-09 18:27:15.803: E/AndroidRuntime(686): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
07-09 18:27:15.803: E/AndroidRuntime(686): at java.lang.StringToReal.parseDouble(StringToReal.java:248)
07-09 18:27:15.803: E/AndroidRuntime(686): at java.lang.Double.parseDouble(Double.java:295)
07-09 18:27:15.803: E/AndroidRuntime(686): at com.manparvesh.Soil.USCS_Open.onCreate(USCS_Open.java:42)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.Activity.performCreate(Activity.java:5008)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
07-09 18:27:15.803: E/AndroidRuntime(686): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
07-09 18:27:15.803: E/AndroidRuntime(686): ... 11 more
I am not able to find the problem here.
Check your following code -
int s10 = Integer.parseInt(S10.getText().toString());
int s40 = Integer.parseInt(S40.getText().toString());
int s200 = Integer.parseInt(S200.getText().toString());
int LL = Integer.parseInt(ll.getText().toString());
int PI = Integer.parseInt(pi.getText().toString());
Exception is thrown because one of the field value (out of s10, s40, s200, LL, PI) is blank. And you are doing Integer.parseInt(""); on that field value.
NumberFormatException
if string cannot be parsed as an integer value.
Solution 1-
Put the block inside try-catch -
int s10 = 0, s40 = 0, s200 = 0, LL = 0, PI = 0;
try{
s10 = Integer.parseInt(S10.getText().toString());
s40 = Integer.parseInt(S40.getText().toString());
s200 = Integer.parseInt(S200.getText().toString());
LL = Integer.parseInt(ll.getText().toString());
PI = Integer.parseInt(pi.getText().toString());
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
Solution 2-
Put this if block just after EditText findView declared and then do something with
your blank values.
if (("".equals(S10.getText().toString()))||
("".equals(S200.getText().toString())) ||
("".equals(S40.getText().toString())) ||
("".equals(LL.getText().toString())) ||
("".equals(PI.getText().toString())))
{
//EditText field value is blank Do something
}
You can assign a valid integer value for blank field so that it will not give NumberFormatException. This is recommended solution.
You are getting a NumberFormatException when you try to do
int s10 = Integer.parseInt(S10.getText().toString());
S10 is currently empty as you haven't typed while it is being created so you try to do
Integer.parseInt("");
and as a result you get NumberFormatException
Try this...
package com.manparvesh.Soil;
import com.manparvesh.soilclassification.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class myMainScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.classificationsystems);
Button aashtob = (Button) findViewById(R.id.aashto);
aashtob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1){
Intent i = new Intent(myMainScreen.this,AASHTO_Open.class);
startActivity(i);
}
});
Button uscsb = (Button) findViewById(R.id.uscs);
uscsb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
Intent i1 = new Intent(myMainScreen.this,USCS_Open.class);
startActivity(i1);
}
});
Button usdab = (Button) findViewById(R.id.usda);
usdab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v3) {
// TODO Auto-generated method stub
Intent i2 = new Intent(myMainScreen.this,USDA_Open.class);
startActivity(i2);
}
});
}
}
You need to pass the context of your Activity whenever starting a new Activity. Passing applicationContext() will increase the scope and may cause memory leaks in the future. So in order to avoid that change this :
startActivity(new Intent(myMainScreen.this,AASHTO_Open.class));
This will reduce the scope to your Activity.
You are getting a NumberFormatException because when you are trying to read from your TextView it's empty but you are expecting a double value. So you must always enforce a check for that and avoid crashes. You must do something like this :
if(S10.getText().toString() != null && S10.getText().toString().trim().length() > 0){
int s10 = Integer.parseInt(S10.getText().toString());
}
Also have a look at the Java Coding Standards before proceeding to code.
Java Coding Style
I'm completely new to java, so i have started making an app to find the TOTAL by presing add and subtract buttons. I have defined buttons and the text view in FRAGMENT_MAIN.XML, and their functions in main activity.JAVA . After defining the functions of buttons in main activity.java, I'm getting logcat errors in my program and the app is getting unfortunately stoped in android emulator. i am using android sdk version 22.6.4, eclipse ide for java develpers version is 2.0.2.20140224-0000 and eclipse platform version is 4.3.2.v2.140221-1852.
my MainActivity.java
package com.counterehr.abhi;
public class MainActivity extends ActionBarActivity {
int counter;
Button add, sub;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
and FRAGMENT_MAIN.XML is
FRAGMENT_MAIN.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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.counterehr.abhi.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your total is 0"
android:textSize="45sp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDisplay"/>
<Button
android:id="#+id/bAdd"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDisplay"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="Add one"
android:textSize="20sp" />
<Button
android:id="#+id/bSub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/bAdd"
android:layout_centerVertical="true"
android:text="Subtract one"
android:textSize="20sp" />
</RelativeLayout>
on running the application i am getting logcat errors as.
logcat errors
07-01 18:16:17.963: E/Trace(833): error opening trace file: No such file or directory (2)
07-01 18:16:19.675: D/dalvikvm(833): GC_FOR_ALLOC freed 80K, 9% free 2419K/2644K, paused 356ms, total 356ms
07-01 18:16:19.704: I/dalvikvm-heap(833): Grow heap (frag case) to 3.415MB for 960016-byte allocation
07-01 18:16:19.802: D/dalvikvm(833): GC_FOR_ALLOC freed 1K, 7% free 3355K/3584K, paused 97ms, total 97ms
07-01 18:16:20.002: D/dalvikvm(833): GC_CONCURRENT freed <1K, 7% free 3355K/3584K, paused 9ms+33ms, total 201ms
07-01 18:16:20.382: D/dalvikvm(833): GC_CONCURRENT freed <1K, 6% free 3779K/4004K, paused 5ms+4ms, total 52ms
07-01 18:16:20.543: D/AndroidRuntime(833): Shutting down VM
07-01 18:16:20.543: W/dalvikvm(833): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-01 18:16:20.583: E/AndroidRuntime(833): FATAL EXCEPTION: main
07-01 18:16:20.583: E/AndroidRuntime(833): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.counterehr.abhi/com.counterehr.abhi.MainActivity}: java.lang.NullPointerException
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.os.Looper.loop(Looper.java:137)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-01 18:16:20.583: E/AndroidRuntime(833): at java.lang.reflect.Method.invokeNative(Native Method)
07-01 18:16:20.583: E/AndroidRuntime(833): at java.lang.reflect.Method.invoke(Method.java:511)
07-01 18:16:20.583: E/AndroidRuntime(833): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-01 18:16:20.583: E/AndroidRuntime(833): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-01 18:16:20.583: E/AndroidRuntime(833): at dalvik.system.NativeStart.main(Native Method)
07-01 18:16:20.583: E/AndroidRuntime(833): Caused by: java.lang.NullPointerException
07-01 18:16:20.583: E/AndroidRuntime(833): at com.counterehr.abhi.MainActivity.onCreate(MainActivity.java:33)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.Activity.performCreate(Activity.java:5104)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-01 18:16:20.583: E/AndroidRuntime(833): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-01 18:16:20.583: E/AndroidRuntime(833): ... 11 more
07-01 18:16:23.873: I/Process(833): Sending signal. PID: 833 SIG: 9
please! someone help me out of this, i tried every possible thing but not getting the solution.
The problem is that you are mixing up Fragments and Activities, and as such, handling events in the Activity, even though these Views are displayed in the Fragment. Basically you are meant to have a FrameLayout in the Activity, and that's it - the logic is handled in the Fragment.
An example is the following:
public class ContainerActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
this.setContentView(R.layout.activity_container);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (saveInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container_container, new ExampleFragment())
.addToBackStack(null)
.commit();
}
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
}
}
activity_container.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/activity_container_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
ExampleFragment:
public class ExampleFragment extends Fragment implements View.OnClickListener
{
private Button btnOne;
private Button btnTwo;
private Button btnThree;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_example, container, false);
btnOne = (Button) rootView.findViewById(R.id.example_button_one);
btnTwo = (Button) rootView.findViewById(R.id.example_button_two);
btnThree = (Button) rootView.findViewById(R.id.example_button_three);
btnOne.setOnClickListener(this);
btnTwo.setOnClickListener(this);
btnThree.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if (btnOne == v)
{
Toast.makeText(getActivity(), "One.", Toast.LENGTH_LONG).show();
}
else if (btnTwo == v)
{
Toast.makeText(getActivity(), "Two.", Toast.LENGTH_LONG).show();
}
else if (btnThree == v)
{
Toast.makeText(getActivity(), "Three.", Toast.LENGTH_LONG).show();
}
}
}
fragment_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/example_button_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/hello"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"/>
<Button
android:id="#+id/example_button_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/example_button_one"
android:layout_alignRight="#+id/example_button_one"
android:layout_below="#+id/example_button_one"
android:layout_marginTop="30dp"
android:text="#string/hello" />
<Button
android:id="#+id/example_button_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/example_button_two"
android:layout_alignRight="#+id/example_button_two"
android:layout_below="#+id/example_button_two"
android:layout_marginTop="30dp"
android:text="#string/hello" />
</RelativeLayout>
Android-Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ContainerActivity"
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>
And that should be a valid example, it shows how you can use an Activity to display a Fragment, and handle events in that Fragment. It currently doesn't show how the Fragment communicates with the Activity to change to another Fragment, which is by the way done by an interface, which you would make a variable to and store in the onAttach() callback method.
But I did include that as well in the "mildly refined" edition on NullPointerException accessing views in onCreate()
Hi I have an app written that goes from a login page, to another activity with a progress bar, then to another activity with a tab host. If I get rid of the loading page and go from login to the tab host works fine, but if I try to go from login to loading the app stops and says 'Unfortunately application has stopped.' I have checked the logcat and see that there is a null pointer error for the Loading page, but I can't see why. In the intent to go from login to loading I call loading correctly, and the set content view in Loading matches its xml loading_main. Here is my code below, thannks:
Main login activity:
package com.example.loginscreen;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText username=null;
private EditText password=null;
private TextView attempts;
private Button login;
int counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
attempts = (TextView)findViewById(R.id.textView5);
attempts.setText(Integer.toString(counter));
login = (Button)findViewById(R.id.button1);
}
public void login(View view){
if(username.getText().toString().equals("mara") &&
password.getText().toString().equals("mara")){
Toast.makeText(getApplicationContext(), "Login Successful!",
Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,Loading.class));
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
attempts.setBackgroundColor(Color.RED);
counter--;
attempts.setText(Integer.toString(counter));
if(counter==0){
login.setEnabled(false);
}
}
}
#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;
}
}
Loading activity:
package com.example.loginscreen;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class Loading extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_main);
addListenerOnButton();
}
public void addListenerOnButton() {
btnStartProgress = (Button) findViewById(R.id.button1);
btnStartProgress.setOnClickListener( // <== This is line 33
new OnClickListener() {
#Override
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Searching for Driver Card...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// driver card is found
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
});
startActivity(new Intent(Loading.this,LinkTabs.class));
}
});
}
// file download simulator
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}
}
return 100;
}
}
Activity LinkTabs to link all tabs in tab host:
package com.example.loginscreen;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
#SuppressWarnings("deprecation")
public class LinkTabs extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.link_main);
Resources ressources = getResources();
TabHost tabHost = getTabHost();
// First tab
Intent intentAndroid = new Intent().setClass(this, HomePage.class);
TabSpec tabSpecHomePage = tabHost
.newTabSpec("HomePage")
.setIndicator("", ressources.getDrawable(R.drawable.overview))
.setContent(intentAndroid);
// Second tab
Intent intentApple = new Intent().setClass(this, HomePage2.class);
TabSpec tabSpecHomePage2 = tabHost
.newTabSpec("HomePage2")
.setIndicator("", ressources.getDrawable(R.drawable.card_summary))
.setContent(intentApple);
// Third tab
Intent intentWindows = new Intent().setClass(this, HomePage3.class);
TabSpec tabSpecHomePage3 = tabHost
.newTabSpec("HomePage3")
.setIndicator("", ressources.getDrawable(R.drawable.details))
.setContent(intentWindows);
// add all tabs
tabHost.addTab(tabSpecHomePage);
tabHost.addTab(tabSpecHomePage2);
tabHost.addTab(tabSpecHomePage3);
//set Windows tab as default (zero based)
tabHost.setCurrentTab(2);
}
}
Tab activities:
package com.example.loginscreen;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HomePage extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("Overview");
setContentView(textview);
}
}
package com.example.loginscreen;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HomePage2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("Card Summary");
setContentView(textview);
}
}
package com.example.loginscreen;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HomePage3 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("Details");
setContentView(textview);
}
}
Here are the xml files:
//activity_main.xml
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/textView2"
android:ems="10"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignLeft="#+id/editText1"
android:ems="10"
android:inputType="textPassword" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_marginTop="40dp"
android:layout_toLeftOf="#+id/editText1"
android:hint="Password"
android:text="#string/password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView4"
android:layout_alignBottom="#+id/textView4"
android:layout_alignLeft="#+id/button1"
android:text="TextView"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_marginTop="155dp"
android:hint="Username"
android:text="#string/username"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:src="#drawable/tranzlogo1" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_marginTop="26dp"
android:layout_toLeftOf="#+id/textView5"
android:text="#string/attempts"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/textView4" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="36dp"
android:onClick="login"
android:text="#string/Login" />
</RelativeLayout>
//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.example.loginscreen.MainActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/tranzlogo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:src="#drawable/overview"
tools:ignore="ContentDescription" />
</RelativeLayout>
//link_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.example.loginscreen.MainActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/tranzlogo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:src="#drawable/overview"
tools:ignore="ContentDescription" />
</RelativeLayout>
//loading_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="413dp"
android:layout_height="382dp" />
</LinearLayout>
Here is loading_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="413dp"
android:layout_height="382dp" />
</LinearLayout>
Here is the mainfest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loginscreen"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.loginscreen.MainActivity"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HomePage" />
<activity android:name=".HomePage2" />
<activity android:name=".HomePage3" />
<activity android:name=".Loading"/>
<activity android:name=".LinkTabs"/>
</application>
</manifest>
And the logcat output:
06-20 10:22:15.289: W/dalvikvm(29524): threadid=1: thread exiting with uncaught exception (group=0x40cca318)
06-20 10:22:15.299: E/AndroidRuntime(29524): FATAL EXCEPTION: main
06-20 10:22:15.299: E/AndroidRuntime(29524): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loginscreen/com.example.loginscreen.Loading}: java.lang.NullPointerException
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2063)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2088)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread.access$600(ActivityThread.java:134)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.os.Looper.loop(Looper.java:137)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread.main(ActivityThread.java:4744)
06-20 10:22:15.299: E/AndroidRuntime(29524): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 10:22:15.299: E/AndroidRuntime(29524): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 10:22:15.299: E/AndroidRuntime(29524): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-20 10:22:15.299: E/AndroidRuntime(29524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-20 10:22:15.299: E/AndroidRuntime(29524): at dalvik.system.NativeStart.main(Native Method)
06-20 10:22:15.299: E/AndroidRuntime(29524): Caused by: java.lang.NullPointerException
06-20 10:22:15.299: E/AndroidRuntime(29524): at com.example.loginscreen.Loading.addListenerOnButton(Loading.java:33)
06-20 10:22:15.299: E/AndroidRuntime(29524): at com.example.loginscreen.Loading.onCreate(Loading.java:26)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.Activity.performCreate(Activity.java:5008)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
06-20 10:22:15.299: E/AndroidRuntime(29524): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2027)
06-20 10:22:15.299: E/AndroidRuntime(29524): ... 11 more
You have referenced in Your LoadingMain activity the following layout with setContentView:
setContentView(R.layout.loading_main);
But this Layout does not have any button1. Instead, You are trying to reference a button from another layout, from activity_main.xml
btnStartProgress = (Button) findViewById(R.id.button1);
This button1 is inside the activity_main.xml and You cannot reference a button in a layout that is not attached per setContentView. So What You have to do is, add a button to the loading_main.xml, BUT, don´t give it the same id like in the activity main "button1". Sure, it works, to give same ids as long as the right layout is referenced, but id´s should be unique. If the button in the activity_layout should remain, give the id for your button inside loading_main.xml another name, maybe android:id="#+id/loading_main_button_1".
Clearly the error is in xml, you have not added the button here:
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="413dp"
android:layout_height="382dp" />
</LinearLayout>
Try adding the following in your loading_main.xml
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
The complete thing should look like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="413dp"
android:layout_height="382dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
NullPointerExcception
it causes because using null object or not defining value to object.
In Loading.java you have used
setContentView(R.layout.loading_main);
that don't have button1
add button1 in loading_main.xml it or Change layout in setContentView(R.layout.other_layout);
I have a layout with few labels and textviews which I want to update based on a action. For testing I have set up the java MainActivity to load the textviews I want to use on created.
Once I click a button called add, the code is executed and prints that the add button was pushed.
I also want the text area to say add for testing. Later on in the project I will change what is displayed here.
However, once I click the button the program stops. I know that the button works because the print shows up in the log.
I have looked and looked and all I can find is the textfield.settext(); But when using this the error occurs and the program stops.
Below is my XML for the TextView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000066"
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.example.smartshop.MainActivity$PlaceholderFragment" >
<LinearLayout
android1:id="#+id/linearLayout1"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:orientation="vertical" >
<ListView
android1:id="#+id/cartlist"
android1:layout_width="289dp"
android1:layout_height="236dp"
android1:textColor="#color/textc" >
</ListView>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<Button
android1:id="#+id/btnadd"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkaddbutton"
android1:text="Add Item" />
<!-- android1:onClick="clkaddbutton" -->
<android.support.v7.widget.Space
android1:id="#+id/space1"
android1:layout_width="2dp"
android1:layout_height="wrap_content" />
<Button
android1:id="#+id/btnremove"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkremovebutton"
android1:text="Remove Item" />
<!-- android1:onClick = "clkremovebutton" -->
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lblsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:text="Sub Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Tax"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Here is the java code in the MainActivity:
package com.example.smartshop;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import java.lang.*;
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
public void clkaddbutton(View view) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnremove = (Button) findViewById(R.id.btnremove);
btnadd = (Button) findViewById(R.id.btnadd);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
if(tfsubtotal != null){
System.out.println("The subtotal edittext was created");
tfsubtotal.setText("test" );
}
else{
System.out.println("The textview is null");
}
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
I know that the problem is on the tfsubtotal.setText("add"); line because I have tested without it and everything works.
I have also tried to use edit text boxes instead of textviews but I get the same error.
Can anyone suggest what I might be doing wrong?
Thank you.
Below is the android log:
05-22 22:37:21.251: I/System.out(1693): The subtotal edittext was created
05-22 22:37:21.251: D/AndroidRuntime(1693): Shutting down VM
05-22 22:37:21.261: W/dalvikvm(1693): threadid=1: thread exiting with uncaught exception (group=0xb2accba8)
05-22 22:37:21.271: E/AndroidRuntime(1693): FATAL EXCEPTION: main
05-22 22:37:21.271: E/AndroidRuntime(1693): Process: com.example.smartshop, PID: 1693
05-22 22:37:21.271: E/AndroidRuntime(1693): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smartshop/com.example.smartshop.MainActivity}: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Handler.dispatchMessage(Handler.java:102)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Looper.loop(Looper.java:136)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invoke(Method.java:515)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-22 22:37:21.271: E/AndroidRuntime(1693): at dalvik.system.NativeStart.main(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): Caused by: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.example.smartshop.MainActivity.onCreate(MainActivity.java:42)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Activity.performCreate(Activity.java:5231)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-22 22:37:21.271: E/AndroidRuntime(1693): ... 11 more
05-22 22:37:23.451: I/Process(1693): Sending signal. PID: 1693 SIG: 9
Try this:
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
TextView tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void clkaddbutton(View view) {
// tfsubtotal.
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
OR
Why not just do simply like this :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
Button btnRemove = (Button)findViewById(R.id.btnremove);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
btnadd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
});
btnRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("Rem");
}
});
}
I am trying to use the tabhost when I add it to my xml it doesn't look right, and I believe there is something that needs to be done in java, I am trying to set up three tabs with three different classes is this possible?
Here is my 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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Browser History:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call Log"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/call"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Messages"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvSms"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
</LinearLayout>
And I have three different classes, because I am trying to use each tab to open each activity.
Here are the Classes
package com.johnnydicamillo.spybeta;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TabHost;
import android.widget.TextView;
public class AndroidSpybetaActivity extends TabActivity {
/** Called when the activity is first created. */
Resources res;
TabHost tabHost;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
res = getResources();
tabHost = getTabHost();
TabHost.TabSpec spec;
intent = new Intent().setClass(this, Messaging.class);
spec = tabHost.newTabSpec("messaging").setIndicator("Messaging")
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TestingData.class);
spec = tabHost.newTabSpec("Calls").setIndicator("Calls")
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
TextView view = (TextView) findViewById(R.id.hello);
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
null, null, null, null);
mCur.moveToFirst();
int index = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
while (mCur.isAfterLast() == false) {
view.append(" WebSite " + mCur.getString(index));
mCur.moveToNext();
}
}
}
Second
package com.johnnydicamillo.spybeta;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Messaging extends TabActivity{
static TextView messageBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
messageBox = (TextView) findViewById(R.id.tvSms);
}
public static void updateMessageBox(String msg) {
messageBox.append(msg);
}
}
and third
package com.johnnydicamillo.spybeta;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.widget.TextView;
public class TestingData extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.call);
String[] projection = new String[] {
Calls.NUMBER
};
Cursor mCur = managedQuery(CallLog.Calls.CONTENT_URI, projection,
Calls.DURATION + "<?", new String[] { "60" }, Calls.DURATION
+ " ASC");
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i = 0; i < mCur.getColumnCount(); i++) {
view.append(" Number " + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here is my logcat:
08-12 15:19:16.368: D/AndroidRuntime(280): Shutting down VM
08-12 15:19:16.368: W/dalvikvm(280): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
08-12 15:19:16.628: E/AndroidRuntime(280): FATAL EXCEPTION: main
08-12 15:19:16.628: E/AndroidRuntime(280): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.johnnydicamillo.spybeta/com.johnnydicamillo.spybeta.AndroidSpybetaActivity}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.johnnydicamillo.spybeta/com.johnnydicamillo.spybeta.Messaging}; have you declared this activity in your AndroidManifest.xml?
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-12 15:19:16.628: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
08-12 15:19:16.628: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
08-12 15:19:16.628: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-12 15:19:16.628: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-12 15:19:16.628: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
08-12 15:19:16.628: E/AndroidRuntime(280): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.johnnydicamillo.spybeta/com.johnnydicamillo.spybeta.Messaging}; have you declared this activity in your AndroidManifest.xml?
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1404)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.resolveActivityInfo(ActivityThread.java:2473)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:277)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.widget.TabHost.addTab(TabHost.java:213)
08-12 15:19:16.628: E/AndroidRuntime(280): at com.johnnydicamillo.spybeta.AndroidSpybetaActivity.onCreate(AndroidSpybetaActivity.java:31)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-12 15:19:16.628: E/AndroidRuntime(280): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-12 15:19:16.628: E/AndroidRuntime(280): ... 11 more
08-12 15:19:21.929: I/Process(280): Sending signal. PID: 280 SIG: 9
Yes, it is possible.
You can specify each activity (Start an intent) for each tabs in the following manner
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
res = getResources();
tabHost = getTabHost();
TabHost.TabSpec spec;
intent = new Intent().setClass(this, CalendarActivity.class);
spec = tabHost.newTabSpec("calendar").setIndicator("Calendar", res.getDrawable(R.drawable.ic_tab_calendar)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ProfileActivity.class);
spec = tabHost.newTabSpec("profile").setIndicator("Profile", res.getDrawable(R.drawable.ic_tab_profile)).setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
Each activity will have their own content layout views, therefore no need to worry about that in the main layout.
Your main XML layout will be small and simple as
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
I think this is what you want.
It is not possible to have a tab correspond to an activity. The purpose of tabs is to break up one activity into how ever many views if there is too much info display in one view(not to be confused with activity). Here however is how you set up TabHost:
First start with an xml:
<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
-
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
-
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<AnalogClock
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="A semi-random button" />
</FrameLayout>
</LinearLayout>
</TabHost>
Sorry that's hard to read but if you copy it into eclipse you should be fine. And then the Java:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;
public class TabDemo extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TabHost tabs=(TabHost)findViewById(R.id.tabhost); //Id of tab host
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("tag1");//make a new tab
spec.setContent(R.id.tab1); //What is in the tab (not an activity but rather a view)
spec.setIndicator("Clock"); //Name of tab
tabs.addTab(spec); //Add it
spec=tabs.newTabSpec("tag2"); //Same thing here
spec.setContent(R.id.tab2);
spec.setIndicator("Button");
tabs.addTab(spec);
}
}
This is relatively simple an I am sure there is support in the android development website and of course just searching on Google. This code was copied out of Beginning Android 4 by Grant Allen and the book explains this topic in much greater detail. Good luck!