on the press of my "next" button I have a speech bubble run through a string array. After all the items finish displaying and the user clicks the "next" button once more I would like to deflate the current child view and inflate a new view. Right now it crashes after the string array finishes displaying on multiple clickings of the "next" button.
How can I get this to work?
package com.jibushi;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class LessonsShell extends Activity{
private static final int MESSAGE_SHOW_POPUP = 1;
private static final int MESSAGE_SHOW_POPUP2 = 1;
private static final long TIME_DELAY = 1000;//1 seconds
private static final long TIME_DELAY2 = 500;
private View view;
private View view2;
private int count = 0;
private TextView lessonsDialog;
private String[] myIntroString;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP:
view();
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lessons);
//this will send a message to the handler to display the popup after 1 seconds.
handler.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP,TIME_DELAY);
}
private void view() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_dialog, null);
parent.addView(view);
lessonsDialog = (TextView) findViewById(R.id.lessonsDialog);
Resources res = getResources();
myIntroString = res.getStringArray(R.array.lessons_dialog_array);
Button nextButton = (Button) findViewById(R.id.next_button);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (count < myIntroString.length) {
lessonsDialog.setText(myIntroString[count]);
count++;
} else {
if (myIntroString[-1] != null) {
handler2.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP2, TIME_DELAY2);
}
}
}
});
}
private Handler handler2 = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP2:
view2();
break;
}
}
private void view2() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view2 = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_start, null);
parent.addView(view2);
parent.removeView(view);
};
};
}
Ah, yes, I see it now. You can't do this:
myString[-1]
The index -1 does not exist in arrays. What are you trying to do? Perhaps myString[count - 1]?
Related
I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}
I'm using customized ListView in android, and using search with customized EditText. When I search for a name, I will get the result using getFilter().filter(cs);. But, when I rotate, the ListView shows the full list (without filtering), then after a delay, it shows the filtered list.
When I rotate without filtering, it maintains the listview position.
So I have to maintain the filtered ListView when I rotate the screen.
Please help. Thanks in advance...
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
#SuppressLint("HandlerLeak")
public class ContactsListActivity
extends Activity
implements LoaderManager.LoaderCallbacks<ArrayList<ListViewItem>> {
private LetterScrollListView mLSListView;
private ProgressBar mProgressBar;
private EditText mSearchText;
private ProgressBar mSearchProgressBar;
private LinearLayout mViewsLl;
private ContactAdapter mFullContactAdapter = null;
private ArrayList<ListViewItem> mFullContactsArrayList = null;
public boolean isSoftKeyOn = false;
public boolean isPortrait;
private long mLastTimeTextChanged = 0L;
private long mCurrentTime = 0L;
private Filter mFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_list);
RelativeLayout windowRl = (RelativeLayout) findViewById(R.id.window_RelativeLayout);
LinearLayout progressBarLl = (LinearLayout) windowRl.findViewById(R.id.progressBar_LinearLayout);
mViewsLl = (LinearLayout) windowRl.findViewById(R.id.views_LinearLayout);
mSearchText = (EditText) mViewsLl.findViewById(R.id.contact_SearchEditText);
mSearchProgressBar = (ProgressBar) mViewsLl.findViewById(R.id.search_ProgressBar);
mLSListView = (LetterScrollListView) mViewsLl.findViewById(R.id.contacts_LetterScrollListView);
mLSListView.setSearchText(mSearchText);
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
isPortrait = true;
} else {
isPortrait = false;
}
final View activityRootView = windowRl;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView()
.getHeight() - activityRootView.getHeight();
// if heightDiff > 100 pixels, its probably a keyboard...
if (heightDiff > 100) {
// Toast.makeText(getApplicationContext(), "Key ON",
// Toast.LENGTH_SHORT).show();
isSoftKeyOn = true;
} else {
// Toast.makeText(getApplicationContext(), "Key OFF",
// Toast.LENGTH_SHORT).show();
isSoftKeyOn = false;
mSearchText.clearFocus();
}
}
});
mSearchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
mCurrentTime = System.currentTimeMillis();
if( (mCurrentTime - mLastTimeTextChanged) <= USER_TYPE_DELAY ) {
mSearchInputHandler.removeMessages(WHAT_SEARCH);
}
// preparing message
Bundle bundle = new Bundle();
bundle.putCharSequence(USER_INPUT_KEY, cs);
Message message = mSearchInputHandler.obtainMessage(WHAT_SEARCH);
message.setData(bundle);
mSearchInputHandler.sendMessageDelayed(message, USER_TYPE_DELAY);
mLastTimeTextChanged = mCurrentTime;
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// Create a progress bar to display while the list loads
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
progressBarLl.addView(mProgressBar);
getLoaderManager().initLoader(0, null, this).forceLoad();
}
#SuppressLint("HandlerLeak")
private final Handler mSearchInputHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
CharSequence cs = msg.getData().getCharSequence(USER_INPUT_KEY);
int what = msg.what;
switch(what) {
case WHAT_SEARCH:
// When user changed the Text after a delay
mSearchProgressBar.setVisibility(View.VISIBLE);
mFilter.filter(cs);
break;
}
}
};
public void removeSearchProgressBar() {
mSearchProgressBar.setVisibility(View.INVISIBLE);
}
/**
* Called when a new Loader needs to be created
*/
public Loader<ArrayList<ListViewItem>> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
boolean showInvisible = false;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
(showInvisible ? "0" : "1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return new ContactArrayListLoader(this, uri, projection, selection, selectionArgs, sortOrder);
}
/**
* Called when a previously created loader has finished loading
*/
public void onLoadFinished(Loader<ArrayList<ListViewItem>> loader, ArrayList<ListViewItem> data) {
mProgressBar.setVisibility(View.INVISIBLE);
if(mLSListView.getAdapter() == null) {
mFullContactsArrayList = data;
mFullContactAdapter = new ContactAdapter(this, R.layout.contact_tuple, mFullContactsArrayList);
mFilter = mFullContactAdapter.getFilter();
mLSListView.setAdapter(mFullContactAdapter);
}
}
/**
* Called when a previously created loader is reset, making the data unavailable
*/
public void onLoaderReset(Loader<ArrayList<ListViewItem>> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
//////mListView.setAdapter(new ContactAdapter(this, R.layout.contact_tuple, null));
mProgressBar.setVisibility(View.VISIBLE);
}
}
SOLVED
The problem is on the method
public void onLoadFinished(Loader<ArrayList<ListViewItem>> loader, ArrayList<ListViewItem> data) {....}
On rotation/starting the app, the parameter data in this method is always the complete list and not the filtered list. So to get the filtered list on rotation, just create a static member
private static ArrayList<ListViewItem> sCurrentContactsArrayList = null;
and save before screen rotation like this:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if( TextUtils.isEmpty(mSearchText.getText()) ) {
sCurrentContactsArrayList = null;
} else {
sCurrentContactsArrayList = mFullContactAdapter.getCurrentItems();
}
}
also modify onLoadFinished():
public void onLoadFinished(Loader<ArrayList<ListViewItem>> loader, ArrayList<ListViewItem> data) {
mProgressBar.setVisibility(View.INVISIBLE);
if(mLSListView.getAdapter() == null) {
ArrayList<ListViewItem> contactsAL = null;
if(sCurrentContactsArrayList == null) {
contactsAL = data;
} else {
contactsAL = sCurrentContactsArrayList;
}
mFullContactAdapter = new ContactAdapter(this, R.layout.contact_tuple, contactsAL, data);
if(mFilter == null) mFilter = mFullContactAdapter.getFilter();
mLSListView.setAdapter(mFullContactAdapter);
}
mSearchText.setVisibility(View.VISIBLE);
}
I created a simple crossfade image class for use in my app. But... i have an error i can't fix due to lack of knowledge. I found this post This Handler class should be static or leaks might occur: IncomingHandler but i have no clue how to fix this in my class. It is a very straightforward class. Create, initialize and start to use it.
I hope someone can help me fix this warning and while we are at it, some hints and tips on my code or comments are very welcome too ;)
MainActivity.java
package com.example.crossfadeimage;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
Xfade xfade = new Xfade();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// INIT(current activity, image id's, time between fades, fade speed)
xfade.init(this, new int[]{ R.id.image1, R.id.image2, R.id.image3 }, 3000, 500);
xfade.start();
}
}
Xfade.java
package com.example.crossfadeimage;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
public class Xfade {
private Activity activity;
// Handler
private Handler handlerTimer = new Handler();
private static final int UPDATE_STUFF_ON_DIALOG = 999;
private int updateTime;
private Animation fadeIn;
private Animation fadeOut;
public int[] xfadeImages;
public int xfadeCounter = 1;
public void init(Activity thisActivity, int[] images, int time,
int animationSpeed) {
activity = thisActivity;
xfadeImages = images;
updateTime = time;
// Set Animations
fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(animationSpeed);
fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(animationSpeed);
// Hide all images except the first
// which is always visible
for (int image = 1; image < xfadeImages.length; image++) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[image]);
thisImage.setVisibility(4);
}
}
public void start() {
handlerTimer.removeCallbacks(taskUpdateStuffOnDialog);
handlerTimer.postDelayed(taskUpdateStuffOnDialog, updateTime);
}
private Runnable taskUpdateStuffOnDialog = new Runnable() {
public void run() {
Message msg = new Message();
msg.what = UPDATE_STUFF_ON_DIALOG;
handlerEvent.sendMessage(msg);
// Repeat this after 'updateTime'
handlerTimer.postDelayed(this, updateTime);
}
};
private Handler handlerEvent = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_STUFF_ON_DIALOG: {
crossFade();
}
break;
default: {
super.handleMessage(msg);
}
break;
}
}
};
public void crossFade() {
if (xfadeCounter == 0) {
ImageView lastImage = (ImageView) activity
.findViewById(xfadeImages[xfadeImages.length - 1]);
lastImage.setVisibility(4);
}
if (xfadeCounter < xfadeImages.length) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[xfadeCounter]);
thisImage.setVisibility(0);
thisImage.startAnimation(fadeIn);
xfadeCounter++;
} else {
// Hide all images except the first
// before fading out the last image
for (int image = 1; image < xfadeImages.length; image++) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[image]);
thisImage.setVisibility(4);
}
// Fadeout
ImageView lastImage = (ImageView) activity
.findViewById(xfadeImages[xfadeImages.length - 1]);
lastImage.startAnimation(fadeOut);
// LastImage is faded to alpha 0 so it doesn't have to be hidden
// anymore
xfadeCounter = 1;
}
}
}
This allows you to modify views and have your handler set to static.
package com.testing.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable {
private static final int THREAD_RESULT = 1000;
private TextView mTextView;
private static Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
}
#Override
protected void onResume() {
super.onResume();
mHandler = new CustomHandler(this);
new Thread(this).start();
}
#Override
public void run() {
// Do some threaded work
// Tell the handler the thread is finished
mHandler.post(new Runnable() {
#Override
public void run() {
mHandler.sendEmptyMessage(THREAD_RESULT);
}
});
}
private class CustomHandler extends Handler {
private MainActivity activity;
public CustomHandler(MainActivity activity) {
super();
this.activity = activity;
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case THREAD_RESULT:
activity.mTextView.setText("Success!");
break;
}
}
}
}
I have a popup text view with a next button and onClick I would like to switch the content.
This is what I tried ...cant get it to work. The error im getting is type mismatch cannot convert from void to int
package com.jibushi;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class LessonsShell extends Activity{
private static final int MESSAGE_SHOW_POPUP=7;
private static final long TIME_DELAY=1000;//1 seconds
private View view;
private Button nextButton;
private Button skipButton;
private TextView nextSwitch;
private int tutStrings;
private int tutStrings2;
private int tutStrings3;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP:
view();
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lessons);
//this will send a message to the handler to display the popup after 1 seconds.
handler.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP,TIME_DELAY);
nextSwitch = (TextView) findViewById(R.id.lessonsDialog);
tutStrings = nextSwitch.setText(R.string.lessons_introduction); //type mismatch cannot convert from void to int
tutStrings2 = nextSwitch.setText(R.string.lessons_introduction2); //type mismatch cannot convert from void to int
tutStrings3 = nextSwitch.setText(R.string.lessons_introduction3); //type mismatch cannot convert from void to int
this.nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case tutStrings:
nextSwitch.setText(R.string.lessons_introduction2);
break;
case tutStrings2:
nextSwitch.setText(R.string.lessons_introduction3);
break;
}
}
});
}
private void view() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_dialog, null);
parent.addView(view);
}
public Button getSkipButton() {
return skipButton;
}
public void setSkipButton(Button skipButton) {
this.skipButton = skipButton;
skipButton.findViewById(R.id.skip_button);
}
public Button getNextButton() {
return nextButton;
}
public void setNextButton(Button nextButton) {
this.nextButton = nextButton;
nextButton.findViewById(R.id.next_button);
}
}
Yeah, lack of research. Didn't know about string arrays...finally got it!
package com.jibushi;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class LessonsShell extends Activity{
private static final int MESSAGE_SHOW_POPUP=7;
private static final long TIME_DELAY=1000;//1 seconds
private View view;
private int count = 0;
private TextView lessonsDialog;
private String[] lessonDialogString;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SHOW_POPUP:
view();
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lessons);
//this will send a message to the handler to display the popup after 1 seconds.
handler.sendEmptyMessageDelayed(MESSAGE_SHOW_POPUP,TIME_DELAY);
}
private void view() {
// TODO Auto-generated method stub
ViewGroup parent = (ViewGroup) findViewById(R.id.lessons_bg);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.lessons_dialog, null);
parent.addView(view);
lessonsDialog = (TextView) findViewById(R.id.lessonsDialog);
Resources res = getResources();
myString = res.getStringArray(R.array.lessons_dialog_array);
Button nextButton = (Button) findViewById(R.id.next_button);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (count < lessonDialogString.length) {
lessonsDialog.setText(lessonDialogString[count]);
count++;
}
}
});
}
}
There are a few problems here.
I don't know what you are trying to do here:
nextSwitch = (TextView) findViewById(R.id.lessonsDialog);
tutStrings = nextSwitch.setText(R.string.lessons_introduction); //type mismatch cannot convert from void to int
tutStrings2 = nextSwitch.setText(R.string.lessons_introduction2); //type mismatch cannot convert from void to int
tutStrings3 = nextSwitch.setText(R.string.lessons_introduction3); //type mismatch cannot convert from void to int
the TextView.setText(String) does not return a value so these lines don't make any sense. Are you trying to save the strings themselves?
Also your onClick method has problems as well. The View that is passed to onClick is the actual view that was clicked which in this case will be the nextButton. In your code you are switching on the undefined ints and not the id's of the different views in your activity.
Instead do something like this:
void onClick(View v){
switch(v.getId()){
case R.id.next_button:
setTextViewNextString();
break;
case R.id.prev_button:
setTextViewPrevString();
}
Then you simply define the setTextViewNextString() and setTextViewPrevString() methods
The method setText returns void:
public final void setText (int resid)
(from http://developer.android.com/reference/android/widget/TextView.html#setText%28int%29)
You cannot assign void to int variables. These lines
tutStrings = nextSwitch.setText(R.string.lessons_introduction); //type mismatch cannot convert from void to int
tutStrings2 = nextSwitch.setText(R.string.lessons_introduction2); //type mismatch cannot convert from void to int
tutStrings3 = nextSwitch.setText(R.string.lessons_introduction3); //type mismatch cannot convert from void to int
are wrong.
I think you can solve your problem in this way:
1) Save the IDs in your private variables:
tutStrings = R.string.lessons_introduction;
tutStrings2 = R.string.lessons_introduction2;
tutStrings3 = R.string.lessons_introduction3;
2) Save the strings, getting them from resources:
private String s1, s2, s3;
...
s1 = this.getString(R.string.lessons_introduction);
s2 = this.getString(R.string.lessons_introduction2);
s3 = this.getString(R.string.lessons_introduction3);
3) Now you can use the onClick method:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case tutStrings:
nextSwitch.setText(s2);
break;
case tutStrings2:
nextSwitch.setText(s3);
break;
}
}
Sorry, lack of research on my part. Used string-array.. works perfectly!
Change your Code like this:
tutStrings = this.getString(R.string.lessons_introduction);
tutStrings2 = this.getString(R.string.lessons_introduction2);
tutStrings3 = this.getString(R.string.lessons_introduction3);
Please Note: In onClick you have to replace this with the name of your class e.g. Myclass.getString or just remove the this.
I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....
Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.
Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?
Here's the full code:
package com.me.player
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;
public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{
private int METHOD_TYPE = 0;
private static final int GET_AUDIO = 1;
int CURRENT_POSITION = 0;
int DURATION = 0;
public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
public static final int MAX_TRACKS = 200;
ArrayList<Track> tracks = new ArrayList<Track>();
Artist artist;
private MediaPlayer mp;
private int mSongPlaying = 0;
TextView _player;
#Override
protected void progressRunnableComplete() {
if(isFinishing()){
return;
}
if(METHOD_TYPE == GET_AUDIO){
setList();
}
}
public void setList(){
ListView listview = (ListView)findViewById(R.id.ListView01);
// ListView listview = (ListView)findViewById(R.id.ListView01);
if(listview == null){
setContent(R.layout.artistaudio);
listview = (ListView)findViewById(R.id.ListView01);
}
// listview.addHeaderView();
listview.setCacheColorHint(0);
listview.setAdapter(new TrackListAdapter());
listview.setSelector(R.drawable.listbackground);
listview.setDividerHeight(1);
listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TrackClicked(arg2);
}
});
}
public void TrackClicked(int arg2){
mSongPlaying = arg2;
Track track = tracks.get(arg2);
String url = track.requestInfo("previewURL");
mHandler.post(new PlaySong(url));
// mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
}
public void setDuration(int n) {
DURATION = n;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Audio Clips");
setContent(R.layout.artistaudio);
Object o = getIntent().getParcelableExtra("artist");
if(o!=null){
artist = (Artist)o;
}
progressRunnable(new Runnable(){
public void run(){
getTracks();
}
}, "Loading. Please Wait...",false);
}
protected void getTracks() {
METHOD_TYPE = GET_AUDIO;
if(!DataBaseHelper.isOnline(this)){
RUNNABLE_STATE = RUNNABLE_FAILED;
return;
}
HttpRequest req;
try {
req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
Document doc = req.AutoXMLNoWrite();
NodeList items = doc.getElementsByTagName("e");
tracks= new ArrayList<Track>();
for(int i=0; i<items.getLength(); i++){
Track newsitem = new Track(items.item(i));
tracks.add(newsitem);
}
RUNNABLE_STATE = RUNNABLE_SUCCESS;
} catch (Throwable e) {
RUNNABLE_STATE = RUNNABLE_FAILED;
e.printStackTrace();
}
}
public void onPause(){
super.onPause();
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.release();}catch(Exception e){e.printStackTrace();}
mp = null;
}
private class TrackListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return tracks.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return tracks.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AudioCell blogView = null;
if (convertView != null) {
if(convertView.getClass() == TextView.class){
convertView = null;
}
}
if (convertView == null) {
blogView = new AudioCell(parent.getContext());
}
else {
blogView = (AudioCell) convertView;
}
blogView.display(position);
return blogView;
}
}
/** this class is responsible for rendering the data in the model, given the selection state */
class AudioCell extends RelativeLayout {
TextView _title;
int currentPosition;
public AudioCell(Context mContext) {
super(mContext);
_createUI(mContext);
}
/** create the ui components */
private void _createUI(Context m) {
RelativeLayout.LayoutParams params;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
_player = new TextView(m);
_player.setId(2);
_player.setBackgroundResource(R.drawable.playbtn);
_player.setText(":30");
addView(_player);
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
_player.setLayoutParams(params);
_title = new TextView(m);
_title.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
params.addRule(RelativeLayout.RIGHT_OF, _player.getId());
params.setMargins(0, 10, 0, 10);
_title.setGravity(Gravity.CENTER_VERTICAL);
_title.setLayoutParams(params);
_title.setId(102);
addView(_title);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
// _player.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//
// }
// });
//
}
/** update the views with the data corresponding to selection index */
public void display(int index) {
_title.setText(tracks.get(index).requestInfo("name"));
}
}
private class PlaySong implements Runnable{
String songURL;
public PlaySong(String url){
songURL = url;
}
public void run(){
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
if(mp==null){
createPlayer();
}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}
}
}
public void createPlayer(){
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try{mp.reset();}catch(Exception e){e.printStackTrace();}
// if(mSongPlaying<tracks.size()-1)
// {
// TrackClicked(mSongPlaying+1);
// }
_player.setBackgroundResource(R.drawable.playbtn);
}
#Override
public void onPrepared(MediaPlayer inMP) {
// TODO Auto-generated method stub
mp.start();
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....
Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).
change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);
Inside your TrackClicked method, add this:
getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);