The application App(process com.example.app) has stopped unexpectedly [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
My problem:
I actually want to set the visibility of my ImageView on random basis. I mean each Image View will be Visible randomly after few milliseconds but my my app unexpectedly crashes all the time. Though, I'm new to android development but good at Java J2SE. Please tell me what I'm doing is it a blunder or a mistake by chance? please! thanks in advance!
package com.example.app;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button b;
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
Thread t=new Thread(new MyThread());
t.start();
}
#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;
}
private class MyThread implements Runnable{
Random randomGenerator = new Random();
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.getStackTrace();
}
}
}
}
}
THE EDITED CODE:
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
Random randomGenerator = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
runOnUiThread(new Runnable() //run on ui thread
{
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
}
}
});
}
#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;
}

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
You must be getting an exception as above. You need to update ui on the UI thread. You are updating UI in the thread. Hence the exception and crash.
Inside your thread use runOnUiThread to update UI
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
....
}
}
});
Also remove this I1=new ImageView(this); since you are initializing as I1=(ImageView) findViewById(R.id.imag1);
Edit:
I would recommend using a Handler for this purpose
int n;
Handler m_handler;
Runnable m_handlerTask ;
Random r;
Declare the above as class variables;
Inside the activity onCrate() use a handler as below
r= new Random();
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
n=r.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
}
m_handler.postDelayed(m_handlerTask, 50);
// 50 milli seconds. set this to desired number
}
};
m_handlerTask.run();
And remember to stop the handler when not required
m_handler.removeCallbacks(m_handlerTask);

I think you want full code. You can use timer. see the following code.
public class MainActivity extends Activity {
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
int n;
Timer t;
TimerTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1 = (ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2 = (ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3 = (ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4 = (ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T = (TextView) findViewById(R.id.time);
s = (TextView) findViewById(R.id.score);
startTimer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void startTimer() {
//Random randomGenerator = new Random();
//n=randomGenerator.nextInt(8);
final Random randomGenerator = new Random();
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//n++;
n=randomGenerator.nextInt(8);
if (n == 1) {
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 2) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.VISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 3) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.VISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 4) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.VISIBLE);
}
}
});
}
};
t.scheduleAtFixedRate(task, 0, 1000);
}
}
This will work perfectly. I hope this will help you.

It is perfect ! 100%
package com.example.abc;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
public Button B;
public Button B1;
public TextView S;
int count=0;
Random randomGenerator = new Random();
int n;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
B=new Button(this);
B=(Button)findViewById(R.id.button1);
B.setVisibility(View.INVISIBLE);
B1=new Button(this);
B1=(Button)findViewById(R.id.button2);
B1.setVisibility(View.INVISIBLE);
S=(TextView)findViewById(R.id.score);
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
runThread();
}
private void runThread() {
new Thread() {
public void run() {
while ( i++ < 1200) {
if(i==1200){
startActivity(new Intent(Test.this,Game.class));
break;
}
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
n = randomGenerator.nextInt(4)+1;
if(n==2){
B.setVisibility(View.VISIBLE);
B1.setVisibility(View.INVISIBLE);
}
if(n==4){
B.setVisibility(View.INVISIBLE);
B1.setVisibility(View.VISIBLE);
}
}
});
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}

Related

How to get value from MainActivity?

So I have this main activity:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private volatile boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
public boolean getStopTask() {
return stopTask;
}
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
I was told that I could access getStopTask() from MyTask by getting an instance of MainActivity and accessing that function directly.
I tried that, but I get an error: "Can't create handler inside thread Thread[Thread-6,5,main] that has not called Looper.prepare()".
Here's MyTask:
import android.widget.TextView;
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = mainActivity.getStopTask();
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error happens right after the app hits:
MainActivity mainActivity = new MainActivity();
How can I get the value of stopTask from MyTask?
I would turn boolean stopTask to static and use it instead of getStopTask() this way:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
/*
public boolean getStopTask() {
return stopTask;
}*/
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
MyTask.java:
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
//MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = MainActivity.stopTask;
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Search focusable null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi i did everything about the search query and have no problem in errors but i keep getting a running time error of nullpointerexception
java src code below
package com.developer.bunamay.mplayer;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
public static final PlayUtils PlayerController = PlayUtils.getInstance();
CustomAdapter customAdapter = null;
private MediaFileAdapter mediaFileAdapter = null;
public static final int PICK_FOLDER_REQUEST = 8;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
SeekBar seekBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if (PlayerConstants.SONGS_LIST.size() <= 0) {
PlayerConstants.SONGS_LIST = PlayUtils.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this, R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
} else {
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.SEEKBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayUtils.getDuration(i[0]));
textDuration.setText(PlayUtils.getDuration(i[1]));
seekBar.setProgress(i[2]);
}
};
} catch (Exception e) {
}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try {
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = PlayUtils.getAlbumart(context, data.getAlbumId());
if (albumArt != null) {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(PlayUtils.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
} catch (Exception e) {
}
}
public static void changeButton() {
if (PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI() {
updateUI();
changeButton();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent about = new Intent(MainActivity.this, About.class);
startActivity(about);
break;
case R.id.action_exit:
finish();
break;
}
int id = item.getItemId();
// get music from specific folder
if (id == R.id.folder_music) {
Intent intent = new Intent(this, FolderPickerActivity.class);
startActivityForResult(intent, PICK_FOLDER_REQUEST);
return true;
}
// search songs by title
if (id == R.id.action_search_title) {
PlayerController.SEARCH_TYPE = "TITLE";
return true;
}
// search songs by artist
if (id == R.id.action_search_artist) {
PlayerController.SEARCH_TYPE = "ARTIST";
return true;
}
// search songs by album
if (id == R.id.action_search_album) {
PlayerController.SEARCH_TYPE = "ALBUM";
return true;
}
if (id == R.id.action_sort_title) {
MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_album) {
MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_artist) {
MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_duration) {
MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// init menu items for search
MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);
SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();
searchViewTitle.setFocusable(true);
searchViewAlbum.setFocusable(true);
searchViewArtist.setFocusable(true);
// init searchable info for each menu item
searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewTitle.setQueryHint("title...");
searchViewTitle.setIconified(true);
searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewAlbum.setQueryHint("album...");
searchViewAlbum.setIconified(true);
searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewArtist.setQueryHint("artist...");
searchViewArtist.setIconified(true);
// set textChangeListeners for each type of search
final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
// apply listeners to searchViews
searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);
return super.onCreateOptionsMenu(menu);
}
}
I keep getting the error on
searchViewTitle.setFocusable(true);
and the here is the logcat displaying the error
07-31 18:12:18.047 2066-2066/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.developer.bunamay.mplayer, PID: 2066
java.lang.NullPointerException
at com.developer.bunamay.mplayer.MainActivity.onCreateOptionsMenu(MainActivity.java:300)
at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:800)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-31 18:12:18.051 587-599/? W/ActivityManager: Force finishing activity com.developer.bunamay.mplayer/.MainActivity
THANKS!!
ActionView of itemSearchTitle is null at this moment.

Application stops after progress bar reaching 100

I built a small progress bar. When you press a button, the progress bar starts counting, from 1 to 100.
I changed the button text to "Running" when it runs. But when I tried to change the text to "Again?" after it reached 100 (after the while loop finished), the application has suddenly stopped - every time.
Any help? Thank you in advance.
package com.myfirstapplication.owner.myfirstapplication;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextClock;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar pg;
Button bt;
int progressStatus = 0;
TextView tv;
Handler handler = new Handler();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pg = (ProgressBar) findViewById(R.id.progressBar);
bt = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.textID);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
#Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bt.setText("Again?");
}
}).start();
}
});
}
}
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
#Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.post(new Runnable() {
#Override
public void run() {
bt.setText("Again?");
}
});
}
}).start();
}
});

Android cannot be referenced from a static context

I'm a beginner on Android and this is the first I'm creating an app named GeoQuiz which basically has a few questions and the user has to click true/false or request the answer with the cheat button.I'm getting this one line of error related with a non-static an a static context in line 138,what am I doing wrong? I'm trying that every time i click on the button cheat, it open the other window that is under a different .xml file and in an another java class
package com.example.fusion.geoquiz;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
import android.content.Intent;
import android.content.Intent;
import java.util.*;
import static com.example.fusion.geoquiz.R.string.correct_toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ProgressBar mProgress;
private Button mCheatButton;
private int mProgressStatus = 0;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private int checker = 0;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private void disablePrev(){
if(mCurrentIndex== 0){
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(false);
}
else{
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(true);
}
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
checker++;
if(checker >0) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
//mProgressStatus=checker;
//mProgress.setProgress(mProgressStatus);
disablePrev();
}
} else {
messageResId = R.string.incorrect_toast;
checker = 0;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
disablePrev();
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
updateQuestion();
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(false);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
disablePrev();
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentIndex != 0){
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mQuestionTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
}
});
disablePrev();
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quiz, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the class for the cheat class and cheatButton
package com.example.fusion.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
/**
* Created by fusion on 1/21/2015.
*/
public class cheatActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
}
}
Replace
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
with
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
See the docs for more details..
Not sure what you're doing there, but you need to reference the other activity class. Simply calling startActivity is enough, because it will be implicitly called from QuizActivity.this.
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
To save you from future errors choose one activity class that you will be using either Activity or ActionBarActivity. The latter is from the support package.

Transition to a black screen

I believe I have my code set up correctly but when I try to debug it, after it transitions from the splash screen it just goes right to a black screen. I know I imported the layout correctly but it still goes black.
This is the code for the splash screen
package com.example.equate.jones;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class EJ_Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ej__splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(4000);
}
}
catch(InterruptedException e) {
// do nothing
} {
finish();
Intent i = new Intent(getApplicationContext(),EJ_Board.class);
startActivity(i);
}
}
};
splashTread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ej__splash, menu);
return true;
}
}
This is the code for the screen it is supposed to transition to.
package com.example.equate.jones;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class EJ_Board extends Activity {
private ImageView button1;
final MediaPlayer mp = MediaPlayer.create(this, R.raw.warm);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ej_board);
button1=(ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
mp.start();
}
});
}
}
This is the xml for EJ_Board
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
I think your problem is with the ImageView. You need to add an image to your drawable folder, then change your android:src="#drawable/ic_launcher" to the name of the image you saved. This will give you the image you need for your button. Hope that helps
Edit:
For your splash screen, try something like this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent homeIntent = new Intent().setClass(SplashActivity.this, HomeActivity.class);
startActivity(homeIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Then in your home activity you can set your menu:
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.locationButton:
Intent locationIntent = new Intent(this, LocationActivity.class);
startActivity(locationIntent);
return true;
case R.id.diningButton:
Intent diningIntent = new Intent(this, DiningActivity.class);
startActivity(diningIntent);
return true;
case R.id.topXXVButton:
Intent topIntent = new Intent(this, DiningActivity.class);
startActivity(topIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(EJ_Splash.this, EJ_Board.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}

Categories