Null pointer exception switching to search in Pocketsphinx Demo - java

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

Related

Null Pointer Exception in string

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.

Android application unable to run on emulator

I'm quite new to android development, I'm trying to develop a server-client application where the server is a simple java application that reads some text from a file and sends it using output stream. the client is an android application that reads this stream when clicking a button and displays it on a text view.
I'm using eclipse with ADK, and testing on an emulator here's how both codes look like:
Server:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
System.out.println("***********Starting ***********");
ServerSocket servsock = new ServerSocket(12344);
System.out.println("Waiting...");
Socket sock = servsock.accept();
while (true)
{
System.out.println("Accepted connection : " + sock);
File myFile = new File ("source.txt");
while (true){
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
}
}
Client:
-MainActivity
package com.example.streamerclient;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button ConnectBtn ;
#Override
public void onResume() {
super.onResume();
//setContentView(R.layout.activity_main);
System.out.println(" on resume ");
ConnectBtn = (Button)findViewById(R.id.ConnectButton);
ConnectBtn.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Connecting c = new Connecting();
}
}
-Connecting class
package com.example.streamerclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.widget.TextView;
public class Connecting extends Activity implements Runnable
{
private Socket sock;
private BufferedReader r;
private BufferedWriter out;
TextView Data;
public Connecting ()
{
Data = (TextView) findViewById(R.id.DataTextView);
Thread th = new Thread(this);
th.start();
}
#Override
public void run() {
try
{
System.out.println("trying to initiated ");
Data.setText("trying to initiated ");
sock = new Socket("10.0.2.2",12344);
System.out.println(" socket initiated ");
Data.setText(" socket initiated ");
r = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Data.setText(" buffer reader initiated ");
System.out.println(" buffer reader initiated ");
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
Data.setText(" buffer writer initiated ");
System.out.println(" buffer writer initiated ");
final String data = r.readLine();
Data.setText(" Data read is: \n"+data);
System.out.println(" Data read is: \n"+data);
}
catch (IOException ioe) { }
}
public void OnPause()
{
System.out.println(" paused");
try {
if (sock != null) {
sock.getOutputStream().close();
sock.getInputStream().close();
sock.close();
System.out.println(" everything is closed ");
}
} catch (IOException e) {}
}
}
I know I know, there are some parts of the code that are not used .. my next task is to have this application send commands to the server ... so I'm still experimenting.
when running the application on the emulator it stops before even displaying any of the GUI components. Any idea why ? Here's what the log file says
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:30.886: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.016: W/Trace(846): Unexpected value from nativeGetEnabledTags: 0
03-17 08:16:31.126: I/System.out(846): on resume
03-17 08:16:31.447: D/AndroidRuntime(846): Shutting down VM
03-17 08:16:31.447: W/dalvikvm(846): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
03-17 08:16:31.457: E/AndroidRuntime(846): FATAL EXCEPTION: main
03-17 08:16:31.457: E/AndroidRuntime(846): java.lang.RuntimeException: Unable to resume activity {com.example.streamerclient/com.example.streamerclient.MainActivity}: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2235)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.os.Looper.loop(Looper.java:137)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 08:16:31.457: E/AndroidRuntime(846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 08:16:31.457: E/AndroidRuntime(846): at dalvik.system.NativeStart.main(Native Method)
03-17 08:16:31.457: E/AndroidRuntime(846): Caused by: java.lang.NullPointerException
03-17 08:16:31.457: E/AndroidRuntime(846): at com.example.streamerclient.MainActivity.onResume(MainActivity.java:20)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.Activity.performResume(Activity.java:5182)
03-17 08:16:31.457: E/AndroidRuntime(846): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
03-17 08:16:31.457: E/AndroidRuntime(846): ... 12 more
thanks!
Try moving the contents of your entire onResume() to an onCreate() method. Always do the UI setup in onCreate(). Read this: Activity Lifecycle Management.
And take any further queries to stackoverflow :)
Cheers!
You are getting a NullPointerException on line 20 in MainActivity, check that line.
I think this question is better suited for stackoverflow

nullpointerexception cannot start activity

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.

Music Player - Function doesn't work when trying to use objects

I am making a music player application for my Computing project. I got it working but found that using objects would get more more marks. As a result, I changed some of my code to incorporate the use of objects, but it doesn't work when I execute my application. Btw I am quite new to Java so it's possible I made a silly mistake.
When I used this code the function I tried to implement worked:
private void SongTitleEndTime(){
try {
TextViewSongTitle = (TextView)findViewById(R.id.songTitle);
if (id != 0 ){
String where = MediaStore.Audio.Media._ID + " = " + "'" + id + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID.toString(), MediaStore.Audio.Media.ALBUM_ID.toString()}, where , null,
null);
mCursor.moveToFirst();
String title = mCursor.getString(0);
String artist = mCursor.getString(1);
String name = title + " - " + artist;
TextViewSongTitle.setText(name);
String fulltime;
albumfullid = Long.parseLong(mCursor.getString(3));
TextView EndTime = (TextView) findViewById(R.id.endtime);
long Minutes = TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration());
long Seconds = TimeUnit.MILLISECONDS.toSeconds(mMediaPlayer.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration()));
if (Seconds < 10) {
String second = "0" + String.valueOf(Seconds);
fulltime = Minutes + ":" + second;
} else {
//else display as normal
fulltime = Minutes + ":" + Seconds;
}
EndTime.setText(fulltime);
//display the duration of song
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} //catch for errors
}
But when I tried this, I got an error:
Main Class:
private void SongTitleEndTime() {
try {
final TextView TextViewSongTitle = (TextView) findViewById(R.id.songTitle);
if (CurrentSongID != 0) {
final Song CurrentSong = new Song(CurrentSongID);
SongName = CurrentSong.SongName;
TextViewSongTitle.setText(SongName);
AlbumID = CurrentSong.AlbumID;
final TextView EndTime = (TextView) findViewById(R.id.endtime);
final String TotalSongDuration = CurrentSong.TotalDuration;
EndTime.setText(TotalSongDuration);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
Object Class:
package com.example.music.test;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
public class Song extends Activity {
private final String where;
public String SongName;
public long AlbumID;
public String TotalDuration;
public Song(final long SongID) {
where = MediaStore.Audio.Media._ID + " = " + "'" + SongID + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID.toString(),
MediaStore.Audio.Media.ALBUM_ID.toString() }, where, null, null);
mCursor.moveToFirst();
final String SongTitle = getSongTitle(mCursor);
final String SongArtist = getSongArtist(mCursor);
SongName = SongTitle + " - " + SongArtist;
AlbumID = getAlbumID(mCursor);
TotalDuration = getTotalDuration();
}
public String getSongTitle(final Cursor mCursor) {
final String songtitle = mCursor.getString(0);
return songtitle;
}
public String getSongArtist(final Cursor mCursor) {
final String songartist = mCursor.getString(1);
return songartist;
}
public long getAlbumID(final Cursor mCursor) {
final long AlbumID = Long.parseLong(mCursor.getString(3));
return AlbumID;
}
public String getTotalDuration() {
String TotalTime;
final long Minutes = TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration());
final long Seconds = TimeUnit.MILLISECONDS
.toSeconds(Player.mMediaPlayer.getDuration())
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration()));
if (Seconds < 10) {
final String second = "0" + String.valueOf(Seconds);
TotalTime = Minutes + ":" + second;
} else {
TotalTime = Minutes + ":" + Seconds;
}
return TotalTime;
}
}
The error I get is:
01-02 21:55:41.941: E/AndroidRuntime(717): FATAL EXCEPTION: main
01-02 21:55:41.941: E/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.music.test/com.example.music.test.Player}: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Looper.loop(Looper.java:137)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 21:55:41.941: E/AndroidRuntime(717): at dalvik.system.NativeStart.main(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): Caused by: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.managedQuery(Activity.java:1737)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Song.<init>(Song.java:21)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.SongTitleEndTime(Player.java:90)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.AllActivities(Player.java:80)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.onCreate(Player.java:66)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.performCreate(Activity.java:5008)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 21:55:41.941: E/AndroidRuntime(717): ... 11 more
Song is an Activity. Thus you can't call manageQuery before onCreate has been called. That's your error.

Code keeps thowing a NPE, cannot find the cause

i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
 Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.

Categories

Resources