I am getting a null pointer exception in my code.Please help me to solve it .
Here is my code.
package com.example.game;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class GuessActivity extends ListActivity implements OnClickListener
{
EditText GNum;
Button nxt;
int[] a = new int[4];
int[] d = new int[4];
int[] b = {0,0,0,0,0,0,0,0};
int[] c = {0,0,0,0,0,0,0,0};
int[] x = new int[8];
int t = 0;
String [] gN = new String[8];
String [] gB = new String[8];
String [] gC = new String[8];
ListAdapter adapter;
/*ArrayList<HashMap<String, String>> output = new ArrayList<HashMap<String, String>>();
HashMap<String, String> out = new HashMap<String, String>();*/
//String KEY_NUM = "1" , KEY_BULLS="2" , KEY_COWS="3";
private class list
{
TextView guess;
TextView bulls;
TextView cows;
}
list lv = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.guess_activity);
GNum = (EditText) findViewById(R.id.etGuessNum);
nxt = (Button) findViewById(R.id.btNxt);
int y = getIntent().getExtras().getInt("num");
for(int i=0;i<4;i++)
{
a[i] = y%10;
y = y/10;
}
/*adapter = new SimpleAdapter(this,output,R.layout.list_item,
new String[]{KEY_NUM , KEY_BULLS , KEY_COWS},new int[]{
R.id.tvGuessNum , R.id.tvBulls , R.id.tvCows});*/
nxt.setOnClickListener(this);
GNum.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if(v.getId() == R.id.btNxt)
{
t++;
if(t>8)
{
Toast.makeText(getApplicationContext(), "You Lost the Game",
Toast.LENGTH_SHORT).show();
return;
}
else
{
gN[t-1] = GNum.getText().toString();
int l = gN[t-1].length();
if(l!=4)
{
Toast.makeText(getApplicationContext(),"Number should be of 4 digits",
Toast.LENGTH_LONG).show();
return;
}
else
{
x[t-1] = Integer.parseInt(gN[t-1]);
for(int i=0;i<4;i++)
{
d[i] = x[t-1]%10;
x[t-1] = x[t-1]/10;
}
if(d[0] == a[0])
b[t-1]++;
if(d[0] == a[1] || d[0] == a[2] || d[0] == a[3])
c[t-1]++;
if(d[1] == a[1])
b[t-1]++;
if(d[1] == a[0] || d[1] == a[2] || d[1] == a[3])
c[t-1]++;
if(d[2] == a[2])
b[t-1]++;
if(d[2] == a[1] || d[2] == a[0] || d[2] == a[3])
c[t-1]++;
if(d[3] == a[3])
b[t-1]++;
if(d[3] == a[1] || d[3] == a[2] || d[3] == a[0])
c[t-1]++;
if(b[t-1] == 4)
{
Toast.makeText(getApplicationContext(), "You Win",
Toast.LENGTH_SHORT).show();
return;
}
gB[t-1] = Integer.toString(b[t-1]);
gC[t-1] = Integer.toString(c[t-1]);
lv = new list();
lv.guess = (TextView) findViewById(R.id.tvGuessNum);
lv.bulls = (TextView) findViewById(R.id.tvBulls);
lv.cows = (TextView) findViewById(R.id.tvCows);
lv.guess.setText(gN[t-1]);
lv.bulls.setText(gB[t-1]);
lv.cows.setText(gC[t-1]);
/*out.put(KEY_NUM, gN[t-1]);
out.put(KEY_BULLS ,String.valueOf(b[t-1]));
out.put(KEY_COWS , String.valueOf(c[t-1]));
output.add(t-1 , out);
setListAdapter(adapter);*/
}
}
}
else if(v.getId()==R.id.etGuessNum)
{
GNum.setText("");
}
}
}
Here is my log cat.
03-08 02:58:55.760: E/AndroidRuntime(861): FATAL EXCEPTION: main
03-08 02:58:55.760: E/AndroidRuntime(861): Process: com.example.game, PID: 861
03-08 02:58:55.760: E/AndroidRuntime(861): java.lang.NullPointerException
03-08 02:58:55.760: E/AndroidRuntime(861): at com.example.game.GuessActivity.onClick(GuessActivity.java:138)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.view.View.performClick(View.java:4438)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.view.View$PerformClick.run(View.java:18422)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Handler.handleCallback(Handler.java:733)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Handler.dispatchMessage(Handler.java:95)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Looper.loop(Looper.java:136)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-08 02:58:55.760: E/AndroidRuntime(861): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 02:58:55.760: E/AndroidRuntime(861): at java.lang.reflect.Method.invoke(Method.java:515)
03-08 02:58:55.760: E/AndroidRuntime(861): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-08 02:58:55.760: E/AndroidRuntime(861): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-08 02:58:55.760: E/AndroidRuntime(861): at dalvik.system.NativeStart.main(Native Method)
line 138 is in on click method -> if -> else ->else ->lv.bulls.setText(gB[t-1];
Probably because you haven't instantiated lv anywhere. It's initialized as null in the beginning and the same value is used at line 138.
Probably your lv.bulls is null. Please make sure you have TextView with id = tvBulls (case-sensitive) at your layout.
Related
I want to develop an speech recognizer in android. I've used this thread and this video to use speech recognition in android device.
Here is my code :
MainActivity.java:
package com.example.pocket_sphinx;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import android.os.Bundle;
import android.app.Activity;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.SpeechRecognizer;
public class MainActivity extends Activity implements RecognitionListener {
private static final String KWS_SEARCH = "wakeup";
private static final String DICTATION_SEARCH = "digits";
private static final String KEYPHRASE = "oh mighty computer";
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(MainActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
recognizer.startListening(KWS_SEARCH);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
Log.d("Spoken text",text);
if (text.equals(KEYPHRASE))
switchSearch(DICTATION_SEARCH);
else
((TextView) findViewById(R.id.result_text)).setText(text);
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
Log.d("end","In end of speech");
if (DICTATION_SEARCH.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
//.setFloat("-beam", 1e-30f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(DICTATION_SEARCH, languageModel);
}
}
Actually I have no idea how to use it. after running ,it is throwing a runtime exception. I've posted the logcat of my code:
03-08 14:02:53.040: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(99): 788 unique initial diphones
03-08 14:02:53.230: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(148): 0 root, 0 non-root channels, 58 single-phone words
03-08 14:02:53.250: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(186): Creating search tree
03-08 14:02:53.470: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(192): before: 0 root, 0 non-root channels, 58 single-phone words
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(326): after: max nonroot chan increased to 2230
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdtree.c(339): after: 253 root, 2102 non-root channels, 13 single-phone words
03-08 14:02:55.630: I/cmusphinx(17309): INFO: ngram_search_fwdflat.c(157): fwdflat: min_ef_width = 4, max_sf_win = 25
03-08 14:02:57.130: W/dalvikvm(17309): threadid=2: spin on suspend #1 threadid=11 (pcf=0)
03-08 14:02:57.140: W/dalvikvm(17309): threadid=2: spin on suspend resolved in 1010 msec
03-08 14:02:57.150: D/-heap(17309): GC_CONCURRENT freed 417K, 8% free 7863K/8455K, paused 14ms+1015ms, total 1597ms
03-08 14:02:57.210: I/SpeechRecognizer(17309): Start recognition "wakeup"
03-08 14:02:57.390: I/cmusphinx(17309): INFO: pocketsphinx.c(863): Writing raw audio log file: /mnt/sdcard/Android/data/com.example.pocket_sphinx/files/sync/000000000.raw
03-08 14:02:57.890: I/SpeechRecognizer(17309): Stop recognition
03-08 14:02:57.890: I/SpeechRecognizer(17309): Start recognition "wakeup"
03-08 14:02:57.890: W/dalvikvm(17309): threadid=1: thread exiting with uncaught exception (group=0x41ab9450)
03-08 14:02:57.930: E/AndroidRuntime(17309): FATAL EXCEPTION: main
03-08 14:02:57.930: E/AndroidRuntime(17309): java.lang.NullPointerException
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.example.pocket_sphinx.MainActivity.switchSearch(MainActivity.java:108)
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.example.pocket_sphinx.MainActivity.access$2(MainActivity.java:105)
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.example.pocket_sphinx.MainActivity$1.onPostExecute(MainActivity.java:67)
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.example.pocket_sphinx.MainActivity$1.onPostExecute(MainActivity.java:1)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.os.AsyncTask.finish(AsyncTask.java:631)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.os.Looper.loop(Looper.java:137)
03-08 14:02:57.930: E/AndroidRuntime(17309): at android.app.ActivityThread.main(ActivityThread.java:4802)
03-08 14:02:57.930: E/AndroidRuntime(17309): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 14:02:57.930: E/AndroidRuntime(17309): at java.lang.reflect.Method.invoke(Method.java:511)
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
03-08 14:02:57.930: E/AndroidRuntime(17309): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580)
03-08 14:02:57.930: E/AndroidRuntime(17309): at dalvik.system.NativeStart.main(Native Method)
03-08 14:02:57.940: I/cmusphinx(17309): INFO: pocketsphinx.c(863): Writing raw audio log file: /mnt/sdcard/Android/data/com.example.pocket_sphinx/files/sync/000000001.raw
You have two issues with your code:
1) You start search inside doInBackground and start the same search again in onPostExecute, you can just call switchSearch in onPostExecute, that would be enough
2) You do not fill captions array but you use it in switchSearch method. So you get null pointer exception. You can comment out
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
in switchSearch if you are not going to use captions
I have followed a tutorial which shows you how you can connect to an rss feed, and pull down the data into a listView. The problem is, is that I want to be able to loop through multiple feeds adding them to the same listView, but when I try to do this....it brings back the following logCat error.
If anyone can help me, that would be great thanks!
Code:
package com.androidhive.xmlparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
String[] URL = new String[2];
int count = 0;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssRun();
}
public void rssRun()
{
URL[0] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < 2;f++)
{
count+=1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
if (count==2)
{
setListAdapter(adapter);
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
}
LogCat:
08-27 09:34:39.786: E/Error:(30651): Expected a quoted string (position:DOCDECL #1:50 in java.io.StringReader#42be4218)
08-27 09:34:39.786: D/AndroidRuntime(30651): Shutting down VM
08-27 09:34:39.786: W/dalvikvm(30651): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 09:34:39.786: E/AndroidRuntime(30651): FATAL EXCEPTION: main
08-27 09:34:39.786: E/AndroidRuntime(30651): Process: com.androidhive.xmlparsing, PID: 30651
08-27 09:34:39.786: E/AndroidRuntime(30651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Looper.loop(Looper.java:157)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 09:34:39.786: E/AndroidRuntime(30651): at dalvik.system.NativeStart.main(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): Caused by: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:57)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:38)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Activity.performCreate(Activity.java:5426)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
I am using methods to shorten my onCreate method
But When I'm trying my app I got force close!
Help please to solve this problem
Activity Class (Main):
package ir.TeenStudio.ActivitiesManagement;
import java.util.ArrayList;
import java.util.HashMap;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
public class Main extends Activity {
public static SQLiteDatabase ActivitiesListDatabase;
private SlidingMenu slidingMenu;
private ActivitiesExpandableListAdapter activitiesListViewAdapter;
private ArrayList<String> groupsList;
private HashMap<String, ArrayList<HashMap<String, String>>> childsList;
private ArrayList<HashMap<String,String>> todayChildsList;
private ArrayList<HashMap<String,String>> tomarrowChildsList;
private ArrayList<HashMap<String,String>> futureChildsList;
private ArrayList<HashMap<String,String>> oneDayChildsList;
private ExpandableListView mylist;
private TextView DayTextView;
private TextView MonthTextView;
private TextView YearTextView;
private Button mainActivity;
private Button ListActivity;
private Button Setting;
private Button Contact;
private Button Information;
private ImageButton Menu;
private ImageButton Add;
private Typeface Rezvan;
private Typeface DroidNaskh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
slidingMenu = new SlidingMenu(this);
activitiesListViewAdapter = new ActivitiesExpandableListAdapter(Main.this, groupsList, childsList);
groupsList = new ArrayList<String>();
childsList = new HashMap<String, ArrayList<HashMap<String,String>>>();
todayChildsList = new ArrayList<HashMap<String,String>>();
tomarrowChildsList = new ArrayList<HashMap<String,String>>();
futureChildsList = new ArrayList<HashMap<String,String>>();
oneDayChildsList = new ArrayList<HashMap<String,String>>();
mylist = (ExpandableListView) findViewById(R.id.activitiesListView);
DayTextView = (TextView) findViewById(R.id.day);
MonthTextView = (TextView) findViewById(R.id.month);
YearTextView = (TextView) findViewById(R.id.year);
mainActivity = (Button) findViewById(R.id.button_main_activity);
ListActivity = (Button) findViewById(R.id.button_lists_activity);
Setting = (Button) findViewById(R.id.button_setting);
Contact = (Button) findViewById(R.id.button_contact);
Information = (Button) findViewById(R.id.button_info);
Menu = (ImageButton) findViewById(R.id.menu_button);
Add = (ImageButton) findViewById(R.id.add_button);
Rezvan = Typeface.createFromAsset(getAssets(), "fonts/rezvan.ttf");
DroidNaskh = Typeface.createFromAsset(getAssets(), "fonts/droid_naskh.ttf");
// Sliding Menu
setSlidingMenu();
//TypoGraphy
setLayoutTypoGraphy();
//LayoutProgramming
setTime();
setButtonsEvent();
//Creating Database
try {
final String path = Environment.getDataDirectory() +"/data/" + getPackageName() + "/ActivitiesList.db";
ActivitiesListDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.CREATE_IF_NECESSARY);
String query ="CREATE TABLE IF NOT EXISTS Content(";
query += "Id INTEGER PRIMARY KEY AUTOINCREMENT,";
query += "Description TEXT,";
query += "AddLocation INTEGER,";
query += "Location TEXT,";
query += "AddDate INTEGER,";
query += "DateYear INTEGER,";
query += "DateMonth INTEGER,";
query += "DateDay INTEGER,";
query += "AddHour INTEGER,";
query += "Hour INTEGER,";
query += "Minutes INTEGER,";
query += "AddAlarm INTEGER,";
query += "AlarmTime INTEGER,";
query += "AddSpecial INTEGER)";
ActivitiesListDatabase.execSQL(query);
Log.d("Database", "Database Created");
} catch (Exception e) {
Log.e("Database", "Database Error");
}
//Receive Data From Database
receiveDataFromDatabase();
//Sending Data to ListView
mylist.setAdapter(activitiesListViewAdapter);
}
#Override
protected void onResume() {
super.onResume();
receiveDataFromDatabase();
activitiesListViewAdapter.notifyDataSetChanged();
}
public void setLayoutTypoGraphy() {
DayTextView.setTypeface(Rezvan);
MonthTextView.setTypeface(Rezvan);
YearTextView.setTypeface(Rezvan);
mainActivity.setTypeface(DroidNaskh);
ListActivity.setTypeface(DroidNaskh);
Setting.setTypeface(DroidNaskh);
Contact.setTypeface(DroidNaskh);
Information.setTypeface(DroidNaskh);
}
public void setTime() {
DayTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay());
YearTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear());
int solarMonth = Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth());
switch (solarMonth) {
case 1:
MonthTextView.setText("فروردین");
break;
case 2:
MonthTextView.setText("اردیبهشت");
break;
case 3:
MonthTextView.setText("خرداد");
break;
case 4:
MonthTextView.setText("تیر");
break;
case 5:
MonthTextView.setText("مرداد");
break;
case 6:
MonthTextView.setText("شهریور");
break;
case 7:
MonthTextView.setText("مهر");
break;
case 8:
MonthTextView.setText("آبان");
break;
case 9:
MonthTextView.setText("آذر");
break;
case 10:
MonthTextView.setText("دی");
break;
case 11:
MonthTextView.setText("بهمن");
break;
case 12:
MonthTextView.setText("اسفند");
break;
}
}
public void receiveDataFromDatabase() {
groupsList.clear();
childsList.clear();
todayChildsList.clear();
tomarrowChildsList.clear();
futureChildsList.clear();
oneDayChildsList.clear();
groupsList.add("امروز");
groupsList.add("فردا");
groupsList.add("آینده");
groupsList.add("یه روز");
Cursor cr = ActivitiesListDatabase.rawQuery("SELECT * FROM Content", null);
if (cr.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Description", cr.getString(cr.getColumnIndex("Description")));
map.put("AddDate", cr.getString(cr.getColumnIndex("AddDate")));
map.put("AddLocation", cr.getString(cr.getColumnIndex("AddLocation")));
map.put("Location", cr.getString(cr.getColumnIndex("Location")));
map.put("DateYear", cr.getString(cr.getColumnIndex("DateYear")));
map.put("DateMonth", cr.getString(cr.getColumnIndex("DateMonth")));
map.put("DateDay", cr.getString(cr.getColumnIndex("DateDay")));
map.put("AddHour", cr.getString(cr.getColumnIndex("AddHour")));
map.put("Hour", cr.getString(cr.getColumnIndex("Hour")));
map.put("Minutes", cr.getString(cr.getColumnIndex("Minutes")));
map.put("AddAlarm", cr.getString(cr.getColumnIndex("AddAlarm")));
map.put("AlarmTime", cr.getString(cr.getColumnIndex("AlarmTime")));
map.put("AddSpecial", cr.getString(cr.getColumnIndex("AddSpecial")));
if (Integer.parseInt(cr.getString(cr.getColumnIndex("AddDate")))==1) {
if(Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay())){
todayChildsList.add(map);
}
else if (Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==(Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay()))+1) {
tomarrowChildsList.add(map);
}
else {
futureChildsList.add(map);
}
} else oneDayChildsList.add(map);
} while (cr.moveToNext());
}
childsList.put(groupsList.get(0), todayChildsList);
childsList.put(groupsList.get(1), tomarrowChildsList);
childsList.put(groupsList.get(2), futureChildsList);
childsList.put(groupsList.get(3), oneDayChildsList);
}
public void setSlidingMenu() {
slidingMenu.setMode(SlidingMenu.RIGHT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowDrawable(R.drawable.menu_shadow);
slidingMenu.setShadowWidth(30);
slidingMenu.setFadeDegree(1.0f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int menu_width = width - width / 3;
if (menu_width < 100) {
menu_width = 100;
}
slidingMenu.setBehindWidth(menu_width);
slidingMenu.setMenu(R.layout.main_right);
}
public void setButtonsEvent() {
OnClickListener ButtonsEvents = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu_button:
slidingMenu.toggle();
break;
case R.id.add_button:
Intent popUpAddItemDialogActivity = new Intent(Main.this, AddItem.class);
startActivity(popUpAddItemDialogActivity);
break;
case R.id.button_main_activity:
//Start main activity
break;
case R.id.button_lists_activity:
//Start lists activity
break;
case R.id.button_setting:
//Start setting
break;
case R.id.button_contact:
//Start contact activity
break;
case R.id.button_info:
//Start info activity
break;
default:
break;
}
}
};
Menu.setOnClickListener(ButtonsEvents);
Add.setOnClickListener(ButtonsEvents);
}
}
And this is my Manifest Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.TeenStudio.ActivitiesManagement"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/name_application"
android:theme="#style/AppTheme" >
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Splash"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Main" android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen">
</activity>
<activity android:theme="#android:style/Theme.Dialog" android:name="AddItem"></activity>
</application>
</manifest>
Log
08-24 22:10:53.325: E/AndroidRuntime(2144): FATAL EXCEPTION: main
08-24 22:10:53.325: E/AndroidRuntime(2144): Process: ir.TeenStudio.ActivitiesManagement, PID: 2144
08-24 22:10:53.325: E/AndroidRuntime(2144): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.TeenStudio.ActivitiesManagement/ir.TeenStudio.ActivitiesManagement.Main}: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Handler.dispatchMessage(Handler.java:102)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Looper.loop(Looper.java:136)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invoke(Method.java:515)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-24 22:10:53.325: E/AndroidRuntime(2144): at dalvik.system.NativeStart.main(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): Caused by: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.setLayoutTypoGraphy(Main.java:140)
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.onCreate(Main.java:91)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Activity.performCreate(Activity.java:5231)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-24 22:10:53.325: E/AndroidRuntime(2144): ... 11 more
Any Idea? Help me plz to solve this
There is no Button with id = button_main_activity in your layout, so mainActivity field is null when you try to use it in setLayoutTypoGraphy method
I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..
I keep getting nullpointerexception errors when I try to start a second activity from my main activity, my main activity code goes as such:
package com.cep.daredevil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public boolean filled = true;
EditText taskArray[] = new EditText[200];
EditText descArray[] = new EditText[200];
String taskArr[] = new String[200];
String descArr[] = new String[200];
int taskId[] = new int[200];
int descId[] = new int[200];
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
Button addfield = new Button(this);
addfield.setText("+");
llayout.addView(addfield);
addfield.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
addtask();
}
});
for(int i=0;i<3;i++)
{
addtask();
}
LinearLayout blayout = (LinearLayout)findViewById(R.id.blayout);
Button submit = new Button(this);
submit.setText("Enter Dare");
Button viewdare = new Button(this);
viewdare.setText("View Dares");
blayout.addView(submit);
blayout.addView(viewdare);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
inputdare(null);
}
});
viewdare.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
listdare();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void addtask()
{
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
taskArray[n] = new EditText(this);
taskArray[n].setHint("Task Title");
taskArray[n].setId(n+10000000);
taskArray[n].setPadding(26,30,25,8);
descArray[n] = new EditText(this);
descArray[n].setHint("Task Description");
descArray[n].setId(n+20000000);
llayout.addView(taskArray[n]);
llayout.addView(descArray[n]);
n++;
}
public void inputdare(View v){
EditText daretitle = (EditText)findViewById(R.id.title);
String dare = daretitle.getText().toString();
for (int i=0;i<n;i++)
{
if (taskArr[i] != null)
{
taskArr[i] = taskArray[i].getText().toString();
}
Integer id = taskArray[i].getId();
if (id != null)
{
taskId[i] = id;
}
}
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putStringArray("TASKS", taskArr);
bundle.putIntArray("TASKID", taskId);
bundle.putBoolean("INPUT", true);
intent.putExtras(bundle);
startActivity(intent);
}
}
public void listdare()
{
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putBoolean("INPUT", false);
intent.putExtras(bundle);
startActivity(intent);
}
}
the function that seems to be causing the problem is in my second activity, over here:
package com.cep.daredevil;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DisplayDares extends Activity {
public final static String PREFS = "Preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_dare);
setupActionBar();
Bundle bundle = getIntent().getExtras();
Boolean input = bundle.getBoolean("INPUT");
if (input == false){}
else
{
int[] taskId = bundle.getIntArray("TASKID");
final String[] taskArray = bundle.getStringArray("TASKS");
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
TextView test = (TextView)findViewById(taskId[0]);
test.setText(taskArray[1]);
layout.addView(test);
}
}
}
the error I get is this:
03-08 13:32:18.053: E/AndroidRuntime(6873): FATAL EXCEPTION: main
03-08 13:32:18.053: E/AndroidRuntime(6873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cep.daredevil/com.cep.daredevil.DisplayDares}: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Looper.loop(Looper.java:137)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invoke(Method.java:511)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-08 13:32:18.053: E/AndroidRuntime(6873): at dalvik.system.NativeStart.main(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:32)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Activity.performCreate(Activity.java:5104)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
After pasing your code it seems line 34 is:
layout.addView(test);
So this line generates a nullpointer exception
Check if the id of your layout is the same.
Tip:
Further in your error stacktrace you can see what causes the error:
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:34)
DisplayDares.java:34
Means line 34 in your DisplayDares.java file.
You will see it is the following line:
layout.addView(test);
Now test cannot be NULL because it wouldn't have thrown that error. So layout must be.