Illegal state exception onclick - java

I am trying to retrieve data by clicking on a button in my activity. I have declared an onclick in activity_second.Here is my code.I am getting am IllegalstateException: method cannot be executed in activity.what is wrong with my code.Why the logcat is showing InvocationTargetException.what exactly this error is and why NullPointerException is there??
public class SecondActivity extends Activity {
private EditText loadinfo;
private Button butn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
loadinfo = (EditText)findViewById(R.id.editText1);
butn1 = (Button)findViewById(R.id.button1);
}
public void apurv1(View view){
File folder = getCacheDir();
File myfile = new File(folder, "mydata1.txt");
String data = readdata(myfile);
if(data!=null){
loadinfo.setText(data);
}
else {
loadinfo.setText("no entry was done");
}
}
private String readdata(File myfile){
FileInputStream fis= null;
try {
fis = new FileInputStream(myfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int read = -1;
StringBuffer stringbuffer = new StringBuffer();
try {
while((read = fis.read())!=-1){
stringbuffer.append((char)read);
}
return stringbuffer.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
StackTrace is
04-26 00:59:00.545: E/AndroidRuntime(2023): FATAL EXCEPTION: main
04-26 00:59:00.545: E/AndroidRuntime(2023): java.lang.IllegalStateException: Could not execute method of the activity
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$1.onClick(View.java:3633)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View.performClick(View.java:4240)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$PerformClick.run(View.java:17721)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Handler.handleCallback(Handler.java:730)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Handler.dispatchMessage(Handler.java:92)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.os.Looper.loop(Looper.java:137)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invoke(Method.java:525)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-26 00:59:00.545: E/AndroidRuntime(2023): at dalvik.system.NativeStart.main(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): Caused by: java.lang.reflect.InvocationTargetException
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 00:59:00.545: E/AndroidRuntime(2023): at java.lang.reflect.Method.invoke(Method.java:525)
04-26 00:59:00.545: E/AndroidRuntime(2023): at android.view.View$1.onClick(View.java:3628)
04-26 00:59:00.545: E/AndroidRuntime(2023): ... 11 more
04-26 00:59:00.545: E/AndroidRuntime(2023): Caused by: java.lang.NullPointerException
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.example.storageexternal.SecondActivity.readdata(SecondActivity.java:62)
04-26 00:59:00.545: E/AndroidRuntime(2023): at com.example.storageexternal.SecondActivity.apurv1(SecondActivity.java:36)
04-26 00:59:00.545: E/AndroidRuntime(2023): ... 14 more

Assuming activity_second is your xml file and you have an attribute android:onClick="readdate" for your button, your readdate method should return void and have an argument of View, such as
public void readdate (View v) {
//add code
}
or via an OnClickListener
Check this post for more details How exactly does the android:onClick XML attribute differ from setOnClickListener?

Related

How to start Activity in my adapter?

How can I start activity in adapter? I use this method in my adapter:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context,asabani_cat.class));
}
});
But this worked just for fragment of my app, when I called this code in Activity App suddenly crashed!
Another question that I have, is it the good way to start activity in adapter?
my logcat:
11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: FATAL EXCEPTION: main 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: java.lang.NullPointerException 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.katibehpayam.mahdi.katibehpayam.adapter_common$7.onClick(adapter_common.java:266) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View.performClick(View.java:4377) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:18044) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5306) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
You could try:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(),asabani_cat.class));
}
});
You should post the error from the Logcat so we can help you further. However from what you've shown I can find nothing inherently wrong with your code. Make sure your context is set correctly. Furthermore if you are already in an Activity you do not need to say
context.startActivity(new Intent(context,asabani_cat.class));
you can simply say
startActivity(new Intent(this, asabani_cat.class));
If you are not in an Activity then you need to pass the context like so
MyAdapter myAdapter = new MyAdapter(this);
Then inside your adapter set your context like this:
MyAdapter(Context context) {
this.context = context;
}
EDIT
Your logcat shows a null pointer exception is the cause of your crash. Can you please post the code from adapter_common.java at line 266? Thanks
In kotlin, on your view:
class YourClass: ArrayAdapter<Feature>(), View.OnClickListener{
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var yourView = inflater.inflate(mResource, parent, false)
yourView .setOnClickListener(){
onClick(convertView)
}
}
override fun onClick(v: View?) {
val intent = Intent(mContext, SeckondActivity::class.java)
mContext.startActivity(intent)
}
}

Android Timer SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

After looking fo ther error at least at the fourm and found only answers that speak about 3rd party device keyborad or somthing that caused it(Samsung devices at least)(Iam using my one plus One).
Ive setted a timer for 10 seconds and every time it reached it 3rd time of runnig (i refresh the activity) i got that error SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length.
TimerAttack class code:
#SuppressLint("NewApi")
public class TimeAttack extends Activity implements AnimationListener {
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
TextView textViewTime;
MediaPlayer mpHint;
MediaPlayer mpNext;
MediaPlayer mpWrong;
Animation animationfadein;
Animation animationfadeout;
String fn;
Guesses G;
Score s;
Timer t;
Button [] b = new Button[4];
DatabaseHandler db = new DatabaseHandler(this);
List<String>WrongAnswers=new ArrayList<String>();
int countG=0;//count Guesses
int countA=0;//count right Answers
int countQ=0;//count Questions
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
textViewTime = (TextView) findViewById(R.id.textViewTime);
hint =(Button)findViewById(R.id.hint);
hint.setOnClickListener(hintOnClickListener);
mpHint = MediaPlayer.create(this,R.raw.hint_sound);
mpNext = MediaPlayer.create(this, R.raw.next_flag);
mpWrong = MediaPlayer.create(this, R.raw.wrong_answer);
animationfadein = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animationfadeout = AnimationUtils.loadAnimation(this, R.anim.fade_out);
textViewTime.setText(t.time);
final CounterClass timer = new CounterClass(11000, 1000);
timer.start();
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
WrongAnswers.add(valToAdd1);
Answers.add(valToAdd1);
}
}
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
b[i].startAnimation(animationfadein);
}
}//end of OnCreat
public boolean onOptionsItemSelected(MenuItem item){//actionbar activity
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
#SuppressLint("NewApi")
public void resetQuiz()
{
countQ++;
recreate();
}
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpHint.start();
/*if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
else*/
G.numOfGuesses++;
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
int invisblecount=0;
for(int i=0;i<b.length;i++){
if(invisblecount<2){
String buttonText = b[i].getText().toString();
if(buttonText.equals(WrongAnswers.get(0))||buttonText.equals(WrongAnswers.get(1)))
{
b[i].startAnimation(animationfadeout);
b[i].setVisibility(View.INVISIBLE);
invisblecount++;
}
}
}
}
};
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
mpNext.start();
s.score+=5;
resetQuiz();
}
else
{
mpWrong.start();
Guesses.numOfGuesses++;
countG=Guesses.numOfGuesses;
/*if(Guesses.numOfGuesses==1)
{
//G.setNumOfGuesses(3);
//finish();//כאשר מספר הניחושים
return;
}else
Guesses.numOfGuesses--;*/
if(s.score>0)
s.score-=5;
scorenum.setText(String.valueOf(s.score));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private void pic_view(String pic2) {
// TODO Auto-generated method stub
//גישה לדגל לפי שמו וייבוא התמונה
Log.d("Result from pic function " , pic2);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
String uri ="#drawable/";
uri += pic2;
int imageResource = getResources().getIdentifier(uri, pic2, getPackageName());//הצוות התמונה
Drawable res= getResources().getDrawable(imageResource);//ציור התמונה
imageView.setImageDrawable(res);
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Animatoin Stoped", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
textViewTime.setText(hms);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
Log.d("Time", "More" + textViewTime.getText().toString());
Toast toast = Toast.makeText(getApplicationContext(), "Time's up Lets see what you made so far...", Toast.LENGTH_SHORT);
toast.show();
Intent en = new Intent(TimeAttack.this,Person.class);
String extra = scorenum.getText().toString();
en.putExtra("Score",extra);
startActivity(en);
}
}
}
stacktrace:
04-26 11:26:15.590: I/System.out(5670): 00:00:08
04-26 11:26:15.610: I/System.out(5670): 00:00:03
04-26 11:26:16.590: I/System.out(5670): 00:00:07
04-26 11:26:16.620: I/System.out(5670): 00:00:02
04-26 11:26:17.590: I/System.out(5670): 00:00:06
04-26 11:26:17.630: I/System.out(5670): 00:00:01
04-26 11:26:18.590: I/System.out(5670): 00:00:05
04-26 11:26:19.130: D/yes(5670): Finland
04-26 11:26:19.320: D/into(5670): com.example.flagsgame.Flags#42cc7998
04-26 11:26:19.320: D/into(5670): 147
04-26 11:26:19.320: D/Result from pic function(5670): palau
04-26 11:26:19.420: D/into(5670): com.example.flagsgame.Flags#428a6720
04-26 11:26:19.420: D/into(5670): 119
04-26 11:26:19.460: D/into(5670): com.example.flagsgame.Flags#42d8f3d0
04-26 11:26:19.460: D/into(5670): 37
04-26 11:26:19.490: D/into(5670): com.example.flagsgame.Flags#42b7ff38
04-26 11:26:19.490: D/into(5670): 183
04-26 11:26:19.510: E/MediaPlayer(5670): Should have subtitle controller already set
04-26 11:26:19.510: E/MediaPlayer(5670): Should have subtitle controller already set
04-26 11:26:19.510: E/MediaPlayer(5670): Should have subtitle controller already set
04-26 11:26:19.510: I/System.out(5670): 00:00:10
04-26 11:26:19.510: D/Time(5670): More00:00:01
04-26 11:26:19.530: I/Timeline(5670): Timeline: Activity_launch_request id:com.example.flagsgame time:36376629
04-26 11:26:19.710: W/MediaPlayer-JNI(5670): MediaPlayer finalized without being released
04-26 11:26:19.710: W/MediaPlayer-JNI(5670): MediaPlayer finalized without being released
04-26 11:26:19.720: W/MediaPlayer-JNI(5670): MediaPlayer finalized without being released
04-26 11:26:19.720: W/Bundle(5670): Key Score expected Integer but value was a java.lang.String. The default value 0 was returned.
04-26 11:26:19.730: W/Bundle(5670): Attempt to cast generated internal exception:
04-26 11:26:19.730: W/Bundle(5670): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
04-26 11:26:19.730: W/Bundle(5670): at android.os.Bundle.getInt(Bundle.java:1000)
04-26 11:26:19.730: W/Bundle(5670): at android.content.Intent.getIntExtra(Intent.java:4620)
04-26 11:26:19.730: W/Bundle(5670): at com.example.flagsgame.Person.onCreate(Person.java:40)
04-26 11:26:19.730: W/Bundle(5670): at android.app.Activity.performCreate(Activity.java:5231)
04-26 11:26:19.730: W/Bundle(5670): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 11:26:19.730: W/Bundle(5670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
04-26 11:26:19.730: W/Bundle(5670): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
04-26 11:26:19.730: W/Bundle(5670): at android.app.ActivityThread.access$800(ActivityThread.java:144)
04-26 11:26:19.730: W/Bundle(5670): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
04-26 11:26:19.730: W/Bundle(5670): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 11:26:19.730: W/Bundle(5670): at android.os.Looper.loop(Looper.java:136)
04-26 11:26:19.730: W/Bundle(5670): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-26 11:26:19.730: W/Bundle(5670): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 11:26:19.730: W/Bundle(5670): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 11:26:19.730: W/Bundle(5670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-26 11:26:19.730: W/Bundle(5670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-26 11:26:19.730: W/Bundle(5670): at dalvik.system.NativeStart.main(Native Method)
04-26 11:26:19.800: I/System.out(5670): 00:00:04
04-26 11:26:19.910: I/Timeline(5670): Timeline: Activity_idle id: android.os.BinderProxy#42b40b18 time:36377008
04-26 11:26:19.920: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:19.920: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:19.930: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:19.930: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:20.510: I/System.out(5670): 00:00:09
04-26 11:26:20.800: I/System.out(5670): 00:00:03
04-26 11:26:21.510: I/System.out(5670): 00:00:08
04-26 11:26:21.800: I/System.out(5670): 00:00:02
04-26 11:26:22.510: I/System.out(5670): 00:00:07
04-26 11:26:22.800: I/System.out(5670): 00:00:01
04-26 11:26:23.510: I/System.out(5670): 00:00:06
04-26 11:26:24.050: D/Time(5670): More00:00:01
04-26 11:26:24.060: I/Timeline(5670): Timeline: Activity_launch_request id:com.example.flagsgame time:36381154
04-26 11:26:24.150: W/Bundle(5670): Key Score expected Integer but value was a java.lang.String. The default value 0 was returned.
04-26 11:26:24.150: W/Bundle(5670): Attempt to cast generated internal exception:
04-26 11:26:24.150: W/Bundle(5670): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
04-26 11:26:24.150: W/Bundle(5670): at android.os.Bundle.getInt(Bundle.java:1000)
04-26 11:26:24.150: W/Bundle(5670): at android.content.Intent.getIntExtra(Intent.java:4620)
04-26 11:26:24.150: W/Bundle(5670): at com.example.flagsgame.Person.onCreate(Person.java:40)
04-26 11:26:24.150: W/Bundle(5670): at android.app.Activity.performCreate(Activity.java:5231)
04-26 11:26:24.150: W/Bundle(5670): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 11:26:24.150: W/Bundle(5670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
04-26 11:26:24.150: W/Bundle(5670): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
04-26 11:26:24.150: W/Bundle(5670): at android.app.ActivityThread.access$800(ActivityThread.java:144)
04-26 11:26:24.150: W/Bundle(5670): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
04-26 11:26:24.150: W/Bundle(5670): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 11:26:24.150: W/Bundle(5670): at android.os.Looper.loop(Looper.java:136)
04-26 11:26:24.150: W/Bundle(5670): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-26 11:26:24.150: W/Bundle(5670): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 11:26:24.150: W/Bundle(5670): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 11:26:24.150: W/Bundle(5670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-26 11:26:24.150: W/Bundle(5670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-26 11:26:24.150: W/Bundle(5670): at dalvik.system.NativeStart.main(Native Method)
04-26 11:26:24.270: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:24.270: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:24.270: I/Timeline(5670): Timeline: Activity_idle id: android.os.BinderProxy#426f66b0 time:36381361
04-26 11:26:24.520: I/System.out(5670): 00:00:05
04-26 11:26:25.520: I/System.out(5670): 00:00:04
04-26 11:26:26.520: I/System.out(5670): 00:00:03
04-26 11:26:27.520: I/System.out(5670): 00:00:02
04-26 11:26:28.520: I/System.out(5670): 00:00:01
04-26 11:26:30.240: D/Time(5670): More00:00:01
04-26 11:26:30.250: I/Timeline(5670): Timeline: Activity_launch_request id:com.example.flagsgame time:36387346
04-26 11:26:30.320: W/Bundle(5670): Key Score expected Integer but value was a java.lang.String. The default value 0 was returned.
04-26 11:26:30.320: W/Bundle(5670): Attempt to cast generated internal exception:
04-26 11:26:30.320: W/Bundle(5670): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
04-26 11:26:30.320: W/Bundle(5670): at android.os.Bundle.getInt(Bundle.java:1000)
04-26 11:26:30.320: W/Bundle(5670): at android.content.Intent.getIntExtra(Intent.java:4620)
04-26 11:26:30.320: W/Bundle(5670): at com.example.flagsgame.Person.onCreate(Person.java:40)
04-26 11:26:30.320: W/Bundle(5670): at android.app.Activity.performCreate(Activity.java:5231)
04-26 11:26:30.320: W/Bundle(5670): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 11:26:30.320: W/Bundle(5670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
04-26 11:26:30.320: W/Bundle(5670): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
04-26 11:26:30.320: W/Bundle(5670): at android.app.ActivityThread.access$800(ActivityThread.java:144)
04-26 11:26:30.320: W/Bundle(5670): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
04-26 11:26:30.320: W/Bundle(5670): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 11:26:30.320: W/Bundle(5670): at android.os.Looper.loop(Looper.java:136)
04-26 11:26:30.320: W/Bundle(5670): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-26 11:26:30.320: W/Bundle(5670): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 11:26:30.320: W/Bundle(5670): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 11:26:30.320: W/Bundle(5670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-26 11:26:30.320: W/Bundle(5670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-26 11:26:30.320: W/Bundle(5670): at dalvik.system.NativeStart.main(Native Method)
04-26 11:26:30.370: I/Timeline(5670): Timeline: Activity_idle id: android.os.BinderProxy#42b6b638 time:36387461
04-26 11:26:30.370: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:26:30.370: E/SpannableStringBuilder(5670): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-26 11:27:03.740: W/IInputConnectionWrapper(5670): getExtractedText on inactive InputConnection
04-26 11:27:03.740: W/IInputConnectionWrapper(5670): getTextBeforeCursor on inactive InputConnection
04-26 11:27:03.740: W/IInputConnectionWrapper(5670): getSelectedText on inactive InputConnection
04-26 11:27:03.740: W/IInputConnectionWrapper(5670): getTextAfterCursor on inactive InputConnection
as you can see the timer are still runnig after the error i got.
Error: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
Check in the text fields you enter that there are no blank spaces. The same thing happened to me and it was because sometimes I added words with spaces at the end.

My activity is crashing after adding a listener

I have this code in my MainActivity class:
public class MainActivity extends ActionBarActivity {
Button mButton;
EditText mEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.btnAsk);
mEdit = (EditText)findViewById(R.id.txtQuestion);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),
mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
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;
}
}
}
Everything was just fine, but after adding setOnClickListener() to mButton it started crashing at the very beginning.
Here is the error log:
04-26 14:12:26.255: E/AndroidRuntime(1447): FATAL EXCEPTION: main
04-26 14:12:26.255: E/AndroidRuntime(1447): Process: com.gelasoft.answeringball, PID: 1447
04-26 14:12:26.255: E/AndroidRuntime(1447): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gelasoft.answeringball/com.gelasoft.answeringball.MainActivity}: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.os.Looper.loop(Looper.java:136)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 14:12:26.255: E/AndroidRuntime(1447): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 14:12:26.255: E/AndroidRuntime(1447): at dalvik.system.NativeStart.main(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447): Caused by: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.gelasoft.answeringball.MainActivity.onCreate(MainActivity.java:30)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.Activity.performCreate(Activity.java:5231)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 14:12:26.255: E/AndroidRuntime(1447): ... 11 more
What am I missing here? I know that it is something really small, but I can't spot it right now.
P.S Here is my fragment 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.xx.ss.MainActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/sphereIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:contentDescription="#string/magicBallDescr"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/sphereIcon"
android:orientation="vertical" >
<TextView
android:id="#+id/txtAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:id="#+id/txtQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/textHint"
android:inputType="textMultiLine"
android:lines="8"
/>
<Button
android:id="#+id/btnAsk"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btnAskQ"
android:paddingEnd="#dimen/activity_vertical_margin"
/>
</LinearLayout>
</RelativeLayout>
Replace
mButton = (Button)findViewById(R.id.btnAsk);
with
mButton = (Button)rootView.findViewById(R.id.btnAsk); // this will go in Fragment onCreateView
And move setOnClicklistener code as well to onCreateView.
Hope it helps.
Move this code :
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),
mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
into your fragment's onCreateView() method. It should work then.

android.os.NetworkOnMainThreadException and java.lang.reflect.InvocationTargetException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a problem.
I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !
Please, I'm new to Android and I need your help guys!
My LogCat:
12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9
MainActivity.java
public class MainActivity extends Activity {
Button btnRecupListMed = null;
ListView listeMed = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecupListMed = (Button) findViewById(R.id.btnListMed);
listeMed = (ListView) findViewById(R.id.listMed);
}
public void recupererListMed(View v){
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(sb.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<TextView
android:text="#string/lbl_sehaty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnListMed"
android:text="#string/lbl_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="recupererListMed"
/>
<ListView
android:id="#+id/listMed"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="60dp">
</ListView>
And my Manifest contains the following permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Thanks.
This error comes when you try to make a server call on UI thread.
You should create an AsyncTask and put your server call in it.
And on click of button call execute on the object of asynctask.
Ex:
public class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
return sb;
}
#Override
protected void onPostExecute(String result) {
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(result.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
}
And inside your onClick event:
public void recupererListMed(View v){
new ServiceTask().execute();
}
This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.

Android App crashes right on start

I have an app that's supposed to get some string from a server depending on the webpage, and it crashes every time I run it. I don't understand how to even debug it, and I've tried numerous changes. It started crashing ever since I messed with the GUI, and added the ability to switch views if that provides any sort of help.
Here is the code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener{
private WebView mWebview;
EditText addressBar;
String currentWebpage = "http://www.aljazeera.com/news/americas/2013/07/20137113200544375.html";
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
View main = (View) findViewById(R.layout.activity_main);
View readOut = (View) findViewById(R.layout.read_out);
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("Showing Activity_Main...");
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
super.onCreate(savedInstanceState);
//setContentView(R.menu.main);
addressBar = (EditText)findViewById(R.id.addressBar);
addressBar.setText(currentWebpage);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enables javascript
mWebview.setWebViewClient(new WebViewClient());
System.out.println("Loading Webpage...");
mWebview.loadUrl(currentWebpage);
}
public void speakOut(String text) {
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
if(tts.isLanguageAvailable(Locale.ENGLISH) != -1){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public int speakFull(String text){
switchToRead();
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
speakOut(sentences[i]);
if(i == sentences.length - 1){
return 1;
}
}
return 0;
}
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://someserver.net:8080/" + webPage));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
private class tts extends AsyncTask<String, Void, String>{//Async http request to get text
#Override
protected String doInBackground(String... arg0) {
try {
System.out.println("Running seperate thread for TTS.");
int complete = 0;
while(complete == 0){
System.out.println("Speaking full..");
complete = speakFull(getText(mWebview.getUrl()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
}
}
public void clickPlay(View v){
new tts().execute("");
}
public void clickGo(View v){
if(addressBar.getText() != null){
currentWebpage = addressBar.getText().toString();
System.out.println("Current webpage changed to: " + currentWebpage);
mWebview.loadUrl(currentWebpage);
}
}
public void clickPause(View v){
System.out.println("Clicked pause.");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
System.out.println("Swtiching view to Read.");
viewGroup.removeView(main);
viewGroup.addView(View.inflate(this, R.layout.read_out, null));
}
public void switchToMain(){
System.out.println("Switching view to Main.");
viewGroup.removeView(readOut);
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
}
}
Also here are the numerous errors I encounter when launching my app:
08-01 14:53:10.210: E/Trace(812): error opening trace file: No such file or directory (2)
08-01 14:53:10.600: D/AndroidRuntime(812): Shutting down VM
08-01 14:53:10.631: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:10.660: E/AndroidRuntime(812): FATAL EXCEPTION: main
08-01 14:53:10.660: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:10.660: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:10.660: E/AndroidRuntime(812): ... 11 more
08-01 14:53:27.439: D/AndroidRuntime(860): Shutting down VM
08-01 14:53:27.439: W/dalvikvm(860): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:27.449: E/AndroidRuntime(860): FATAL EXCEPTION: main
08-01 14:53:27.449: E/AndroidRuntime(860): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:27.449: E/AndroidRuntime(860): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): Caused by: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:27.449: E/AndroidRuntime(860): ... 11 more
Move your view initialization inside onCreate after setContentView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
...// rest of the code

Categories