This is my MainActivity.class. I am trying to make a music player app for Android. This player will run in the background. It plays a song but when I press the back button it shows the following errors on line number 105 and 118.
import com.example.shadowman.audio_player_two.MusicService.MusicBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.MediaController.MediaPlayerControl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static android.content.Context.BIND_AUTO_CREATE;
public class MainActivity extends Activity implements MediaPlayerControl {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
//service
private MusicService musicSrv;
private Intent playIntent;
//binding
private boolean musicBound=false;
//controller
private MusicController controller;
//activity and playback pause flags
private boolean paused=false, playbackPaused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve list view
songView = (ListView)findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
//setup controller
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//start and bind the service when the activity starts
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
//user song select
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#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) {
//menu item selected
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
//method to retrieve song info from device
public void getSongList(){
//query external audio
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public void start() {
musicSrv.go();
}
//set the controller up
private void setController(){
controller = new MusicController(this);
//set previous and next button listeners
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
//set and show
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
protected void onPause(){
super.onPause();
paused=true;
}
#Override
protected void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
protected void onStop() {
if(controller !=null) {
controller.hide();
controller=null;
}
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopService(playIntent);
musicSrv=null;
}
}
Here is the error:
Please help me to understand & solve this error
You need to unbind service:
#Override
protected void onStop() {
// your onStop code
if(musicConnection != null) {
unbindService(musicConnection);
}
super.onStop();
}
Related
I am trying to get the result value in a string after there has been scanned.
but it wont work.
I already figured out how to put it in a toast(maketext) that works but a string I cant figure it out.
here's the code please help me.
cpackage com.example.stage.absa;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import java.io.IOException;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.net.Uri;
import java.net.URL;
public class MainActivity extends AbsRuntimePermission {
String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#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);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZxingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
remove the String declaration and instead move it as a class member
public void handleResult(Result result) {
//String resultCode = result.getText();
resultCode = result.getText();
like:
myClass extends Activity... {
String resultCode;
}
now you can assign the result code in the hadnleResult callback and use it in the same activity whenever you need it!
Edit:
you have an inner class, i would get rid of that and directly implement the ZXingScannerView.ResultHandler interface:
example:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#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);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
//scannerView.setResultHandler(new ZxingScannerResultHandler());
scannerView.setResultHandler(this);
setContentView(scannerView);
scannerView.startCamera();
}
//class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
//}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
I will go with this or something similar, depending on how you are handling the scanner view
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private String resultCode;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
resultCode = rawResult.getText();
//now use resultCode
}
}
It's self explanatory. mediarecorder class's start method throws an illegalstateexception the second it's called. First time I press the button it all works fine. The second time it does not. I thread a lot of things and Idk what's wrong. I tried solutions from other questions regarding the media recorder but they didn't help. The permissions are place in the manifest. so that isn't the issue obviously since it works the first time.
MAIN
package com.boomer.omer.notetoself;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class Activity_Main extends Activity implements View.OnTouchListener {
ProgressBar progressBar_record;
Button button_record;
Recorder recorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar_record = (ProgressBar)findViewById(R.id.progressBar_recorder);
button_record = (Button)findViewById(R.id.button_record);
button_record.setOnTouchListener(this);
recorder = 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.menu_activity_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(v.getId()){
case R.id.button_record:
if(event.getAction() == MotionEvent.ACTION_DOWN){
button_record.setText("RECORDING");
startRecorder();
}else if (event.getAction() == MotionEvent.ACTION_UP){
button_record.setText("RECORD");
stopRecorder();
}
break;
}
return false;
}
public void startRecorder(){
recorder = new Recorder(this,progressBar_record);
recorder.execute();
}
public void stopRecorder(){
progressBar_record.setProgress(0);
recorder.cancel(true);
recorder = null;
}
}
RECORDER CLASS
public class Recorder extends AsyncTask<Void,Integer,Void> {
public static final String LOG_TAG = "NTS:";
static final int MAX_LENGTH = 30;
MediaRecorder mRecorder;
String mFileName = null;
ProgressBar recordBar;
Activity parentActivity;
int mLength = 0;
public Recorder(Activity activity,ProgressBar progressBar) {
super();
mFileName = activity.getFilesDir().getAbsolutePath();
mFileName += "/recentRecord.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recordBar = progressBar;
parentActivity =activity;
}
public void startRecording(){
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
public void stopRecording(){
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
mRecorder = null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
startRecording();
}
#Override
protected Void doInBackground(Void... params) {
long secondMillis = System.currentTimeMillis();
while(mLength < MAX_LENGTH){
if((System.currentTimeMillis() - secondMillis) >= 1000){
secondMillis = System.currentTimeMillis();
mLength++;
publishProgress(mLength);
}
}
stopRecording();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
stopRecording();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
recordBar.setProgress(values[0]);
}
#Override
protected void onCancelled(Void aVoid) {
super.onCancelled(aVoid);
stopRecording();
}
#Override
protected void onCancelled() {
super.onCancelled();
stopRecording();
}
}
I Have an app in which the main activity shows a question and has true button false button and cheat button
When user press the correct option, listener will Toast Correct.. and otherwise listener will Toast Incorrect
Now when we press the cheat button new activity is launched and has a textview "Are you sure you want to cheat?", another textview which is blank and a show answer button..
When user presses the show answer button , the blank text view is set to the answer of the question (as asked in the main activity)
And when the user goes back the true and false button onClickListeners are now set to make a toast "Cheating is wrong"
i have declared a boolean value which is set to false, the boolean value is set to True and i save it in the bundle so that when the user rotates the screen , the value of the variable is not overwritten on onCreate(..) method being recalled..
I tried debugging with break points in eclipse , the value is not overridden still on main activity "Cheating is wrong" doesnt show up , it shows Correct or Incorrect..
QuizActivity : Launcher Activity
CheatActivity: Activity launched on onCreate
TrueFalse activity : creating array of objects with fields (question and answer)
Following is the code : QuizActivity.java (Launcher activity)
package com.mhrsolanki2020.geoquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton, mFalseButton, mNextButton, mCheatButton;
private TextView mQuestionTextView;
private static final String KEY_INDEX = "index";
private static final String TAG = "QuizActivity";
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 boolean mIsCheater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mIsCheater=false;
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answer = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answer);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null)
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
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 (mIsCheater) {
messageResId = R.string.judgement_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else {
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN,
false);
Log.d(TAG, "Value of mIsCheater : " + mIsCheater);
}
}
}
The following is the code : CheatActivity.java
package com.mhrsolanki2020.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.mhrsolanki2020.geoquiz.anwer_is_true ";
public static final String EXTRA_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_shown";
public static final String EXTRA_IS_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_is_shown";
boolean mCorrectAnswer;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsAnswerShown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mCorrectAnswer = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,
false);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
if (savedInstanceState != null) {
mIsAnswerShown = savedInstanceState.getBoolean(
EXTRA_IS_ANSWER_SHOWN, false);
} else {
mIsAnswerShown = false;
}
mShowAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mCorrectAnswer) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
}
public void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
mIsAnswerShown = isAnswerShown;
data.putExtra(EXTRA_ANSWER_SHOWN, mIsAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(EXTRA_IS_ANSWER_SHOWN, mIsAnswerShown);
}
}
Following is the code : TrueFalse.java
package com.mhrsolanki2020.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
http://developer.android.com/guide/topics/resources/runtime-changes.html check this link
For orientation support do this in manifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
In Class file, override the onSaveInstanceState(Bundle outState).
I'm attempting to load different activites with this MenuItem when I click the menuitem (specifically - help) the correct activity User1Tap.class does not load (it brings me to the AddEditCountry.class instead)
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class CountryList extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(CountryList.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
case R.id.help:
Intent i = new Intent(ViewCountry.this, User1Tap.class);
CountryList.this.startActivity(i);
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
country_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="schemas.android.com/apk/res/android">;
<item android:id="#+id/addCountryItem"
android:title="#string/add_menu"
android:titleCondensed="#string/add_menu"
android:showAsAction="always"
android:alphabeticShortcut="e"/>
<item android:id="#+id/help"
android:title="#string/help"
android:titleCondensed="#string/help"
android:alphabeticShortcut="e"/>
</menu>
Try this:
case R.id.help:
Intent i = new Intent(this, User1Tap.class);
startActivity(i);
finish();
return true;
call the method setcontentview() in your oncreate() method...
i guesss its missing from there...
try if it works
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
//like this
setcontentview(R.layout.yourlayout);
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
I am developing an app in which i need to fill spinner from one webservice and there are second spinner are also exist which fill after select first spinner item. second(spinner B) is depend on spinner A. i got list for A but problem with b spinner.
my basic requirement is when i select the item of spinner "A" it will load all item of Spinner "b"
here is code ::
package com.CaribPay;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.Setting.CustomParser;
public class Register2 extends Activity implements OnItemClickListener {
private Button BtnReg2Next;
private EditText EdtxReg2Streetadd1,
EdtxReg2Streetadd2,
EdtxReg2City,
EdtxReg2Zipcode;
private Spinner
SpnrReg2Contry,
SpnrReg2Agent,
SpnrReg2State,
SpnrReg2PrimaryCurr,
SpnrReg2SecondaryCurr;
private CustomParser cstParsr = new CustomParser();
private String[] Regstrationstep1;
private String[] strCountry,strProvince;
private String[] Primarysecondarycur;
private int globPosition;
private String strSelecteccontry;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register2);
GetDataFromLastPage();
new FillSpinnerTask().execute();
}
private class FillSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strCountry = cstParsr.LoadCountriesForMobApp(getApplicationContext());
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strCountry != null)
{
for(int i=0;i<strCountry.length;i++)
{
Log.i("TAG","strCountry"+strCountry[i]);
}
}
FillView();
}
}
}
private void FillView() {
BtnReg2Next = (Button)findViewById(R.id.BtnReg2Next);
EdtxReg2Streetadd1 = (EditText)findViewById(R.id.EdtxReg2Streetadd1);
EdtxReg2Streetadd2= (EditText)findViewById(R.id.EdtxReg2Streetadd2);
EdtxReg2City = (EditText)findViewById(R.id.EdtxReg2City);
EdtxReg2Zipcode = (EditText)findViewById(R.id.EdtxReg2Zipcode);
SpnrReg2Contry = (Spinner)findViewById(R.id.SpnrReg2Contry);
SpnrReg2Agent = (Spinner)findViewById(R.id.SpnrReg2Agent);
SpnrReg2State = (Spinner)findViewById(R.id.SpnrReg2State);
SpnrReg2PrimaryCurr = (Spinner)findViewById(R.id.SpnrReg2PrimaryCurr);
SpnrReg2SecondaryCurr= (Spinner)findViewById(R.id.SpnrReg2SecondaryCurr);
if(strCountry != null)
{
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strCountry);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2Contry.setAdapter(languagelist);
}
SpnrReg2Contry.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3)
{
strSelecteccontry = strCountry[position];
new FillProvinceSpinnerTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
/*SpnrReg2State.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(strProvince == null)
{
new FillProvinceSpinnerTask().execute();
}
return true;
}
});*/
BtnReg2Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(EdtxReg2Streetadd1.getText().toString().equalsIgnoreCase("")|
EdtxReg2Streetadd2.getText().toString().equalsIgnoreCase("")|
EdtxReg2City.getText().toString().equalsIgnoreCase("")|
EdtxReg2Zipcode.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getApplication(),getString(R.string.nullmessage),Toast.LENGTH_LONG).show();
}else
{
Intent Registration2 = new Intent(Register2.this,Register3.class);
startActivity(Registration2);
finish();
}
}
});
}
private void GetDataFromLastPage() {
// TODO Auto-generated method stub
Intent intent = getIntent();
Regstrationstep1 = new String[9];
Regstrationstep1 = intent.getStringArrayExtra("Regstrationstep1");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int Pos, long arg3) {
// TODO Auto-generated method stub
}
private class FillProvinceSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strProvince = cstParsr.LoadProvinceFromCountryForMobApp(getApplicationContext(),strSelecteccontry);
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strProvince != null)
{
Primarysecondarycur = strProvince[0].split("~");
strProvince[0] = "Please Select a State";
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strProvince);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2State.setAdapter(languagelist);
}
}
}
}
}
The issue with OnItemSelectedListener is that it selects first value on declaration. To avoid the first call do something like this :
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(count>0) {
// do what you want on item selection
} else {
count++;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}