How To Use Method onProgressChanged for RangeSeekbar? - android

I´ve succesfully implemented the RangeSeekbar from this website ( http://code.google.com/p/range-seek-bar/) into my App.
The Problem alot of people now have tho, is that we can´t find an onProgressChanged Method for the two thumbs in the code for the RangeSeekbar.
Do i have to write my own onProgressChanged?
I implemented the RangeSeekbar into a DialogFragment. For the normal Seekbar everything worked fine.
http://www.directupload.net/file/d/3582/mokh6mkb_jpg.htm <-- How can I get the two TextViews to the left and right of "to" to show the selected Value of the RangeSeekbar?
My Code so far:
package com.example.test2;
import com.example.test2.RangeSeekBar.OnRangeSeekBarChangeListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
public class LookingAgeFragment extends DialogFragment implements View.OnClickListener, OnRangeSeekBarChangeListener {
protected static final String TAG = null;
public static String username;
static int lowestAge;
static int highestAge;
static TextView viewTo, viewMaxAge, viewMinAge;
RangeSeekBar<Integer> seekBar;
public void onAttach(Activity activity){
super.onAttach(activity);
}
public void onCeate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view= inflater.inflate(R.layout.fragment_age_looking,null);
getDialog().setTitle(getString(R.string.lookingage_title));
Button button = (Button)view.findViewById(R.id.buttonLeaveFragmentLookingAge);
viewTo = (TextView)view.findViewById(R.id.textView_to);
viewMaxAge = (TextView)view.findViewById(R.id.textView_maxAge);
viewMinAge = (TextView)view.findViewById(R.id.textView_minAge);
button.setOnClickListener(this);
// create RangeSeekBar as Integer range between 20 and 75
seekBar = new RangeSeekBar<Integer>(20, 75, getActivity());
seekBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
}
});
ViewGroup layout = (ViewGroup) view.findViewById(R.id.rangeSeekbarContainer);
layout.addView(seekBar);
setUpLayout();
return view;
}
#SuppressLint("NewApi")
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Bundle bundle = this.getArguments();
if(bundle != null){
username = bundle.getString("username", null);
}
}
private void setUpLayout() {
// TODO Auto-generated method stub
setCancelable(false);
//bar.setOnSeekBarChangeListener(yourSeekBarListener);
}
public void saveDataChange(String s, String data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(s, data);
editor.commit();
}
public String getData(String s){
String data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getString(s, null);
return data;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.buttonLeaveFragmentLookingAge:
dismiss();
break;
}
}
public void onProgressChanged() {
// TODO Auto-generated method stub
int maxvalue = (Integer) seekBar.getSelectedMaxValue();
viewMaxAge.setText(maxvalue);
int minvalue = (Integer) seekBar.getSelectedMinValue();
viewMinAge.setText(minvalue);
}
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
int maxvalue = (Integer) seekBar.getSelectedMaxValue();
viewMaxAge.setText(maxvalue);
int minvalue = (Integer) seekBar.getSelectedMinValue();
viewMinAge.setText(minvalue);
}
public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue,
Object maxValue) {
// TODO Auto-generated method stub
viewMaxAge.setText((String)maxValue);
viewMinAge.setText((String)minValue);
}
}
Thank you for your help.

RangeSeekbar is a generic class. if your pass T parameter to it as type of range values, then RangSeekBar pass left thumb Value as minValue and right thumb Value as maxValue in
RangeSeekBar.OnRangeSeekBarChangeListener.(RangeSeekBar bar, T minValue, T maxValue).
change line of your class extends to:
public class LookingAgeFragment extends DialogFragment implements OnRangeSeekBarChangeListener<Integer>
after that you should change Object to Integer in your code at this line
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
viewMinAge.setText(String.valueOf(minValue));
viewMaxAge.setText(String.valueOf(minValue));
}
});
I think by this changes your problem will be solved.
for more generic solution when your ages range is not continuous and maybe discrete, I suggest this solution
public class LookingAgeFragment extends DialogFragment implements RangeSeekBar.OnRangeSeekBarChangeListener<Integer> {
RangeSeekBar<Integer> seekBar;
int[] ageValues={10, 20, 30, 50, 100};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// create RangeSeekBar as Integer range between 20 and 75
seekBar = new RangeSeekBar<Integer>(0, ageValues.length - 1, getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
viewMinAge.setText(String.valueOf(ageValues[minValue]));
viewMaxAge.setText(String.valueOf(ageValues[minValue]));
}
});
}
}

I use next code for getting the values on changing event:
rangeSeekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("MinValue", rangeSeekBar.getSelectedMinValue().toString());
Log.d("MaxValue", rangeSeekBar.getSelectedMaxValue().toString());
return false;
}
});

In class ReangeSekkBar you have this if in ACTION_MOVE
if (notifyWhileDragging && listener != null) {
listener.onRangeSeekBarValuesChanged(this, getSelectedMinValue(), getSelectedMaxValue());
}
delete this if
//if (notifyWhileDragging && listener != null) {
listener.onRangeSeekBarValuesChanged(this, getSelectedMinValue(), getSelectedMaxValue());
//}

Related

App crashes immediately after I added SeekBar change listner

Hi I am a total newb to Android Development and I have been banging my head against the wall about this for weeks. Basically I have a SeekBar and I want to have it do something whenever the SeekBar moves. I tried to set up an onSeekBarChange event handler and as soon as I added that the app will not run anymore, and crashes at launch. I have looked all over the place online, and all the examples I find match my code EXACTLY, so I'm just wondering if I am putting it in the wrong place or something. Here is my entire MainActivity class file.
package com.slistersoft.scottlisterlab11;
import java.text.DecimalFormat;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
String custName, phoneNum, carChoice;
double miles, costBeforeTip, tipPercentage, tipAmount, totalCost;
private SeekBar tipBar = null;
public void MsgBox(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void showToast(String message, int durationMS){
Toast.makeText(getApplicationContext(), message, durationMS).show();
}
public void calculateCost(View v){
final EditText nameBox = (EditText)findViewById(R.id.nameBox);
final EditText phoneBox = (EditText)findViewById(R.id.phoneNumber);
final EditText milesBox = (EditText)findViewById(R.id.milesBox);
final Spinner car = (Spinner)findViewById(R.id.carPickerDropDown);
final SeekBar tipBar = (SeekBar)findViewById(R.id.tipBar);
if(nameBox.getText().toString().equals(""))
showToast("Please enter your name", 5000);
else if(phoneBox.getText().toString().equals("") )
showToast("Please enter your phone number",5000);
else if(milesBox.getText().toString().equals(""))
showToast("Please enter the amount of miles you need to travel",5000);
else{
custName = nameBox.getText().toString();
phoneNum = phoneBox.getText().toString();
miles = Double.parseDouble(milesBox.getText().toString());
carChoice = car.getSelectedItem().toString();
costBeforeTip = (3.25 * miles) + 3.00;
tipPercentage = tipBar.getProgress();
tipAmount = (tipPercentage/100) * costBeforeTip;
totalCost = costBeforeTip + tipAmount;
DecimalFormat currency = new DecimalFormat("$###,###.##");
MsgBox("Hello " + custName + ",\n\n" +
"Your estimated cost will be " + currency.format(costBeforeTip) +
"\n\nWith a " + tipPercentage + "% tip of " + currency.format(tipAmount) + " that brings your total cost to " + currency.format(totalCost) +
"\n\nA " + carChoice + " will pick you up ASAP. \n\nWe will call you at " + phoneNum + " when we are getting close. \n\nThank you for using CrAzY TaXi.");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tipBar = (SeekBar)findViewById(R.id.tipBar);
tipBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
If anybody has any ideas on this I would greatly appreciate it.
does the seekbar belong to fragment_main.xml? I am guess it does. So move initialization to onCreateView of fragment. use rootView.findViewById – Raghunandan 10 hours ago

Refreshing a fragment View on back from settings change

What I'm trying to accomplish is have my view refresh when someone comes back from the settings and changes their preference. I thought this would work but it is not. Any ideas on how i can accomplish this?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.projectcaruso.naturalfamilyplanning.R;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
public class ChartingFragment extends Fragment implements OnDateSetListener {
SharedPreferences mPreferences;
Boolean symptothermal;
Boolean mucus_stamps;
Boolean fertile_infertile;
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getChildFragmentManager(), "datePicker");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
symptothermal = mPreferences.getBoolean("symptothermal", true);
mucus_stamps = mPreferences.getBoolean("mucus_stamps", true);
fertile_infertile = mPreferences.getBoolean("fertile_infertil", true);
}
#SuppressLint("SimpleDateFormat")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = setcontrolvisability(inflater);
return view;
}
#Override
public void onResume() {
super.onResume();
View vg = getView().findViewById(R.id.charting);
vg.invalidate();
init();
}
private View setcontrolvisability(LayoutInflater inflater) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_charting, null);
TextView temp;
if (!symptothermal) {
temp = (TextView) view.findViewById(R.id.temp);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.tempvalue);
temp.setVisibility(View.GONE);
}
if (!mucus_stamps) {
temp = (TextView) view.findViewById(R.id.stamp);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.stampvalue);
temp.setVisibility(View.GONE);
}
if (!fertile_infertile) {
temp = (TextView) view.findViewById(R.id.fertile);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.fertileswitch);
temp.setVisibility(View.GONE);
}
temp = (TextView) view.findViewById(R.id.dateselected);
SimpleDateFormat dfDate_day= new SimpleDateFormat("MM/dd/yyyy");
String dt="";
Calendar c = Calendar.getInstance();
dt=dfDate_day.format(c.getTime());
temp.setText(dt);
return view;
}
}
I'd suggest to use startActivityForResult and pass a Bundle if sub-activity (FragmentActivity) has been changed.
1) From your Activity start Preference Activity:
Intent intent = new Intent(this, PreferenceActivity.class);
if (!this.isFinishing())
startActivityForResult(intent, REQUEST_UPDATE);
2) Override onActivityResult
#Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
super.onActivityResult(reqCode, resCode, data);
Log.d(TAG, "Received Result: " + reqCode + " / " + resCode);
}
3) in Subactivity (PreferenceActivity) monitor which keys have been changed and pass it as a bundle if you like
public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener,
OnPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
getParent().setResult(MainActivity.RESULT_PREFERENCES_CHANGED); // constant
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
}

deflate view and inflate another

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]?

Creating a "next" button that switches the content of a TextView

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.

setBackgroundResource of TextView in listitem

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);

Categories

Resources