Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.
Related
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
public class MyAdapter extends BaseAdapter {
private String[] from;
ArrayList <HashMap<String, Object>> BuyList ;
private int[] to;
private Context context;
private ArrayList<HashMap<String, Object>> data ;
private ArrayList<HashMap<String, Object>> selecteddata;
private ArrayList<HashMap<String, Object>> fdata ;
private ImageView pay,more;
private EditText search;
private String user_mobile;
private TextView buy_toolbar_count;
private Holder holder;
// private HashMap<String, Object> hm;
public MyAdapter( Context context, ArrayList<HashMap<String, Object>> data,
ArrayList<HashMap<String, Object>> selecteddata , String[] from, int[] to, ArrayList Bylist,
ImageView pay, ImageView more, String user_mobile, TextView buy_count_toolbar, EditText search) {
this.data = data;
this.selecteddata = selecteddata;
this.fdata = new ArrayList<>(selecteddata);
this.context = context;
this.from = from;
this.to = to;
this.BuyList = Bylist;
this.pay = pay;
this.more = more;
this.search = search;
this.user_mobile = user_mobile;
this.buy_toolbar_count = buy_count_toolbar;
}
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
// Log.i("mosi",wp.get("name").toString() + " wp ");
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
}
notifyDataSetChanged();
}
public class Holder
{
ImageView g_img;
ImageView plus;
ImageView mines;
TextView g_name;
TextView g_price;
TextView g_off;
TextView count;
TextView f_range;
TextView sum;
TextView temp2;
}
#Override
public int getCount() {
return fdata.size();
}
#Override
public HashMap<String, Object> getItem(int i) {
return fdata.get(i);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Typeface font_titr = Typeface.createFromAsset(context.getAssets(), "fonts/titr.TTF");
final HashMap<String, Object> hm = fdata.get(position);
if (convertView == null ) {
holder = new Holder();
convertView = LayoutInflater.from(context).
inflate(R.layout.my_row_layout2, parent, false);
holder.g_img = (ImageView) convertView.findViewById(R.id.f_img);
holder.g_name = (TextView) convertView.findViewById(R.id.f_name);
holder.g_price = (TextView) convertView.findViewById(R.id.f_price);
holder.g_off = (TextView) convertView.findViewById(R.id.f_off);
holder.count = (TextView) convertView.findViewById(R.id.f_count);
holder.f_range = (TextView) convertView.findViewById(R.id.f_kilo);
holder.plus = (ImageView) convertView.findViewById(R.id.plus_id_btn);
holder.mines = (ImageView) convertView.findViewById(R.id.mines_id_btn);
holder.sum = (TextView) convertView.findViewById(R.id.count_sum_id);
holder.temp2 = (TextView) convertView.findViewById(R.id.txt2);
//Date currentTime = Calendar.getInstance().getTime();
convertView.setTag(holder);
// Log.i("mosi",convertView.getTag() + " tagfffff " + hm.get("convertview"));
hm.put("convertview", "1");
}
else
{
holder = (Holder) convertView.getTag();
// Log.i("mosi",convertView.getTag() + " tag " + hm.get("convertview"));
}
final View tempview = convertView;
// set font++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
holder.g_price.setTypeface(font_titr, Typeface.NORMAL);
holder.g_name.setTypeface(font_titr, Typeface.BOLD);
holder.g_off.setTypeface(font_titr, Typeface.NORMAL);
holder.count.setTypeface(font_titr, Typeface.NORMAL);
holder.sum.setTypeface(font_titr, Typeface.NORMAL);
holder.temp2.setTypeface(font_titr, Typeface.NORMAL);
//----------------------------------------------------------------------------------------
// Set pre count and sum
holder.sum.setText(" میلغ کل : " + hm.get("sum").toString() + " تومان ");
holder.count.setText(hm.get("count").toString());
final String oldprice = hm.get("price").toString();
holder.g_off.setText(hm.get("off").toString());
holder.g_name.setText(hm.get("disc").toString());
holder.f_range.setText(hm.get("f_range").toString());
final float f=
(Float.valueOf(oldprice)*
Float.valueOf(holder.g_off.getText().toString()))/100;
// holder.g_price.setText(" قیمت : "+ DtoS((Float.valueOf(oldprice.toString()))-f)+" تومان ");
holder.g_price.setText(" قیمت : "+ oldprice +" تومان ");
File imageFile = new File(hm.get("image").toString());
if(imageFile.exists()){
holder.g_img.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
}
else
holder.g_img.setImageResource(R.drawable.coming_soon);
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "p", tempview, ChangeType.DtoS((Float.valueOf(oldprice.toString())) - f), position);
}
});
holder.mines.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "m", tempview , ChangeType.DtoS((Float.valueOf(oldprice.toString()))-f), position);
}
});
// Button Pay && More
pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (BuyList.size() > 0) {
Intent intent = new Intent(context, Payment_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", BuyList);
intent.putExtra("all_data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
//
} else {
Toast.makeText(context, "سبد خرید شما خالی است", Toast.LENGTH_LONG).show();
}
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Choose_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("blist", BuyList);
intent.putExtra("data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
// ((Activity)context).finish();
}
});
// Search -------------------------------------------------------------------
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
// Log.i("mosi", s+" --- s ***");
// filter(s.toString(), holder.g_img);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
// template
// Onclick for mines and plus Button
//#Override
public void change_count(final Holder holder1, HashMap<String, Object> hm_addtolist, String tag, View c_view, String oldprice, int position) {
// Log.i("mosi", position+" position on list ");
String is_pack = hm_addtolist.get("is_pack").toString();
ChangeType ch = new ChangeType();
double temp1 = 0;
double p_with_off = 0;
holder = (Holder) c_view.getTag();
String off = hm_addtolist.get("off").toString();
String num_sum = "0";
if (ch.stringToDouble(off)>0)
{
p_with_off = ch.stringToDouble(hm_addtolist.get("price_with_off").toString());
}
else
p_with_off = ch.stringToDouble(oldprice.toString());
holder.count= (TextView) c_view.findViewById(R.id.f_count);
holder.sum = (TextView) c_view.findViewById(R.id.count_sum_id);
if (!holder.count.getText().toString().equals("") && holder.count!= null)
temp1 = ch.stringToDouble(holder.count.getText().toString());
//my_alert("", temp1+"");
if (tag.equals("p")) {
if (is_pack.equals("1"))
temp1 = temp1 + 1;
else
temp1 = temp1 + 0.5;
// Log.i("mosi", " ::: set 2 !!!!");
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long)(temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else if (tag.equals("m")) {
if (is_pack.equals("1")) {
if (temp1 > 1) {
temp1 = (temp1 - 1);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
else {
if (temp1 > 0.5) {
temp1 = (temp1 - 0.5);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
hm_addtolist.put("count","0");
hm_addtolist.put("sum","0");
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
}
//}
if (!num_sum.equals("0")) {
hm_addtolist.put("sum", num_sum);
hm_addtolist.put("count", holder.count.getText().toString());
boolean check = false;
for (int i = 0; i < BuyList.size(); i++) {
if (BuyList.get(i).get("name").toString().equals(hm_addtolist.get("name").toString())) {
check = true;
HashMap<String, Object> temp_updatelist = BuyList.get(i);
temp_updatelist.put("sum", num_sum);
temp_updatelist.put("count", holder.count.getText().toString());
// BuyList.add(temp_updatelist);
// Log.i("mosi", "add count "+i+"");
// Toast.makeText(context, "ok", Toast.LENGTH_SHORT);
notifyDataSetChanged();
}
}
if (!check) {
// Log.i("mosi", "add count to :: "+hm_addtolist.get("name")+"");
BuyList.add(hm_addtolist);
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
notifyDataSetChanged();
}
}
notifyDataSetChanged();
// Log.i("mosi", BuyList.toString());
// clearbug( c_view);
}
}
make list on activity
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
private void setlist() {
ArrayList<HashMap<String, Object>> selected_data = new ArrayList<>();
for (int i = 0; i < all_data.size(); i++) {
if (all_data.get(i).get("type").toString().equals(mtag)) {
HashMap<String, Object> t = all_data.get(i);
selected_data.add(t);
}
}
//Log.i("mosi",selected_data.toString());
EditText search = (EditText) findViewById(R.id.et_search_id);
ImageView pay = (ImageView) findViewById(R.id.btn_pay_firstpage);
ImageView more = (ImageView) findViewById(R.id.btn_more_firstpage);
String[] from = {"image", "name", "price", "off"};
int[] to = {R.id.f_img, R.id.f_name, R.id.f_price, R.id.f_off};
final MyAdapter adb = new MyAdapter(getBaseContext(), all_data, selected_data, from, to, BuyList, pay, more, user_mobile, buyCount_toolbar, search);
lv.setAdapter(adb);
}
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
its my activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:background="#drawable/main_background_theme">
<include
android:id="#+id/mytoolbar"
layout="#layout/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"/>
<include
android:id="#+id/app_message"
layout="#layout/message"
android:layout_height="30dp"
android:layout_width="match_parent"
android:layout_below="#+id/mytoolbar"/>
<include
android:id="#+id/searchbox_id"
layout="#layout/searchbox"
android:layout_height="40sp"
android:layout_width="match_parent"
android:layout_below="#+id/app_message"
android:visibility="invisible"/>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchbox_id"
android:id="#+id/FirstPage_id">
<RelativeLayout
android:id="#+id/rv_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainLayoutActivity">
<ListView
android:id="#+id/my_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/listDivader"
android:dividerHeight="1dp"
android:paddingBottom="?attr/actionBarSize" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignBottom="#id/my_listview"
android:background="#color/toolbar_back"
android:orientation="horizontal">
<ImageView
android:id="#+id/btn_pay_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_pay" />
<ImageView
android:id="#+id/btn_more_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_more" />
</LinearLayout>
</RelativeLayout>
<fragment
android:layout_width="180dp"
android:layout_height="match_parent"
android:id="#+id/drawer_fragment"
android:layout_gravity="start"
android:layout="#layout/drawer_fragment_layout"
tools:layout="#layout/drawer_fragment_layout"
android:name="com.com.seyedi89gmail.sm.zanco.Drawer_fragment">
</fragment>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
Remove notifyDataSetChanged from if-else conditions, May this will work
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
//notifyDataSetChanged();
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
//notifyDataSetChanged();
}
notifyDataSetChanged();
}
you can use NestedScrollview outside the listview and stop the scrolling of listview by using this: smoothScrollBy(0, 0);
I am having a problem with cardview not displaying some from the database.
My app connects to a grails back end which has a PostgreSQL db.
I have a cardview inside a recyclerview. It receives 7 values in form of JSON but on running the app, only 5 are displayed. I try doing System.out of the JSON in the stack trace and I find that all the 7 values are received so everything is okay on that front.
For clarity purposes, the fields that are not being displayed are labs("labs") and drugs administered("drugsAdministered").
Here is the main class(ClinicalHistory.java), the adapter class, the xml and the stack-trace.
ClinicalHistory.java
public class ClinicalHistory extends AppCompatActivity {
RecyclerView clinicalHistory_rv;
SwipeRefreshLayout swipeRefreshLayout;
List<com.example.user.eafya.models.ClinicalHistory> clinicalHistory_List;
com.example.user.eafya.models.ClinicalHistory clinicalHistory;
ClinicalHistoryAdapter clinicalHistoryAdapter;
private StringRequest clinicalHistoryRequest;
private LinearLayout no_data;
private LinearLayoutManager linearLayoutManager;
private RequestQueue requestQueue;
private ProgressDialog pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clinical_history);
initWidgets();
fetchData();
}
private void fetchData() {
pb = new ProgressDialog(this);
pb.setIcon(R.mipmap.ic_launcher);
pb.setTitle("Please wait");
pb.setCancelable(false);
pb.setMessage("Loading data..");
pb.show();
clinicalHistoryRequest = new StringRequest(Request.Method.GET, Configs.URL_LOGIN + Configs.CLINICALHISTORY_PATH, new Response.Listener<String>() {
#Override
public void onResponse(String result) {
pb.dismiss();
System.out.print("======================================"+ result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("mVisit");
for (int i=0;i<jsonArray.length();i++){
System.out.print("----------------"+jsonArray.getJSONObject(i).getString("labs"));
}
Log.d("myError: ", String.valueOf(jsonArray.length()));
if(jsonArray.length()<1) {
clinicalHistory_List.clear();
no_data.setVisibility(View.VISIBLE);
}else if( jsonArray.length()>0){
if(no_data.getVisibility()==View.VISIBLE){
no_data.setVisibility(View.GONE);
}
for(int i=0 ; i<jsonArray.length() ; i++){
JSONObject data = jsonArray.getJSONObject(i);
clinicalHistory = new com.example.user.eafya.models.ClinicalHistory();
clinicalHistory.setDate(data.getString("dateCreated"));
clinicalHistory.setHospital(data.getString("hospitalAttended"));
clinicalHistory.setDoctor(data.getString("attendingDoctor"));
clinicalHistory.setLabs(data.getString("labs"));
clinicalHistory.setChiefComplains(data.getString("chiefComplains"));
clinicalHistory.setDrugs(data.getString("drugsAdministered"));
clinicalHistory_List.add(clinicalHistory);
}
clinicalHistoryAdapter = new ClinicalHistoryAdapter(ClinicalHistory.this, clinicalHistory_List);
linearLayoutManager = new LinearLayoutManager(ClinicalHistory.this);
clinicalHistory_rv.setLayoutManager(linearLayoutManager);
clinicalHistory_rv.setItemAnimator(new DefaultItemAnimator());
clinicalHistory_rv.setAdapter(clinicalHistoryAdapter);
clinicalHistory_rv.setSaveEnabled(true);
clinicalHistory_rv.setSaveFromParentEnabled(true);
clinicalHistoryAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
Log.d("MaeraJ",e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
pb.dismiss();
AlertDialog.Builder dialog = new AlertDialog.Builder(ClinicalHistory.this);
dialog.setTitle("Something went wrong !!");
dialog.setCancelable(true);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setMessage("Check your data connection");
dialog.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//retry
dialogInterface.dismiss();
fetchData();
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//cancel
dialogInterface.dismiss();
}
});
dialog.create();
dialog.show();
Log.d("Maera",volleyError.toString());
}
});
requestQueue.add(clinicalHistoryRequest);
}
private void initWidgets() {
requestQueue = Volley.newRequestQueue(this);
no_data = findViewById(R.id.nodata_LY);
clinicalHistory_rv = findViewById(R.id.clinicalHistory_RV);
clinicalHistory_List = new ArrayList<>();
swipeRefreshLayout = findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refresh();
}
});
}
private void refresh() {
try {
clinicalHistory_List.clear();
fetchData();
swipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
}
Adapter class(ClinicalHistoryAdapter.java)
public class ClinicalHistoryAdapter extends RecyclerView.Adapter<ClinicalHistoryAdapter.myViewHolder> {
Context ctx;
List<ClinicalHistory> clinicalHistoryList;
ClinicalHistory clinicalHistoryModel;
LayoutInflater inflater;
public ClinicalHistoryAdapter(Context ctx, List<ClinicalHistory> clinicalHistoryList) {
this.ctx = ctx;
this.clinicalHistoryList = clinicalHistoryList;
inflater = LayoutInflater.from(ctx);
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView clinicalHist_date_TV,clinicalHist_hospital, clinicalHist_doctor,clinicalHist_chiefComplains, clinicalHist_labs, clinicalHist_drugs;
ImageView clinicalHist_img;
public myViewHolder(View itemView) {
super(itemView);
clinicalHist_img = itemView.findViewById(R.id.clinicalHist_image_IV);
clinicalHist_date_TV = itemView.findViewById(R.id.clinicalHist_date__TV);
clinicalHist_hospital = itemView.findViewById(R.id.clinicalHist_hospital_TV);
clinicalHist_doctor = itemView.findViewById(R.id.clinicalHist_doctor);
clinicalHist_chiefComplains = itemView.findViewById(R.id.clinicalHist_chief_complains_TV);
clinicalHist_labs = itemView.findViewById(R.id.clinicalHist_labs_TV);
clinicalHist_drugs = itemView.findViewById(R.id.clinicalHist_drugs_TV);
}
}
#Override
public ClinicalHistoryAdapter.myViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View my_view = inflater.inflate(R.layout.clinical_history_item,viewGroup,false);
return new myViewHolder(my_view);
}
#Override
public void onBindViewHolder(ClinicalHistoryAdapter.myViewHolder myViewHolder, final int position) {
clinicalHistoryModel = new ClinicalHistory();
clinicalHistoryModel = clinicalHistoryList.get(position);
myViewHolder.clinicalHist_date_TV.setText(clinicalHistoryModel.getDate());
myViewHolder.clinicalHist_hospital.setText(clinicalHistoryModel.getHospital());
myViewHolder.clinicalHist_doctor.setText(clinicalHistoryModel.getDoctor());
myViewHolder.clinicalHist_chiefComplains.setText(clinicalHistoryModel.getChiefComplains());
myViewHolder.clinicalHist_labs.setText(clinicalHistoryModel.getLabs());
myViewHolder.clinicalHist_drugs.setText(clinicalHistoryModel.getDrugs());
myViewHolder.clinicalHist_doctor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
myViewHolder.clinicalHist_hospital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
Glide.with(ctx).load(clinicalHistoryModel.getImg()).placeholder(R.drawable.loader).error(R.drawable.header).into(myViewHolder.clinicalHist_img);
}
private void goToDetails(int pos) {
clinicalHistoryModel = clinicalHistoryList.get(pos);
Intent intent = new Intent(ctx,MedicalDetailActivity.class);
intent.putExtra("dateCreated", clinicalHistoryModel.getDate());
intent.putExtra("clinicalHist_img", clinicalHistoryModel.getImg());
intent.putExtra("hospitalAttended", clinicalHistoryModel.getHospital());
intent.putExtra("attendingDoctor", clinicalHistoryModel.getDoctor());
intent.putExtra("chiefComplaints", clinicalHistoryModel.getChiefComplains());
intent.putExtra("labs", clinicalHistoryModel.getLabs());
intent.putExtra("drugs", clinicalHistoryModel.getLabs());
ctx.startActivity(intent);
}
#Override
public int getItemCount() {
return clinicalHistoryList.size();
}
}
The xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="2dp"
android:orientation="horizontal"
android:padding="2dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/clinicalHist_image_IV"
android:layout_width="110dp"
android:layout_height="80dp"
android:layout_gravity="top"
android:scaleType="fitXY"
android:src="#drawable/header" />
<LinearLayout
android:padding="4dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_date__TV"
android:text="21/09/2012"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_hospital_TV"
android:text="Hema Hospital"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:id="#+id/clinicalHist_doctor"
android:text="Dr.Lilian"/>
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_labs_TV"
android:text=" Brucella "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_chief_complains_TV"
android:text=" Headache "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_drugs_TV"
android:text=" Brufen "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The stack trace
I/System.out: ======================================{"mVisit":[{"id":1,"chiefComplains":"Headache","dateCreated":"2017-08-11T21:00:00Z","labs":"Brucella","hospitalAttended":"Hema Hospital","drugsAdministered":"Tramadol","attendingDoctor":"Dr. Kisinga"
I have found the solution. The problem was in the model.
This was my previous model. Note the parameters in the
setDrugs() and setLabs().
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String hospital) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String hospital) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
After I made this change it worked
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String labs) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String drugs) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
I was trying to create a CalendarView in Lollipop when I ran it I didn't get the same design as Marshmallow so I changed to DatePicker but I don't want the header part just the Calendar. Is that possible?
I have tried this code in my MainActivity but with no luck (referring to this link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMonthPicker();
}
public void initMonthPicker() {
DatePicker dp_mes = (DatePicker) findViewById(R.id.datePicker2);
int year = dp_mes.getYear();
int month = dp_mes.getMonth();
int day = dp_mes.getDayOfMonth();
dp_mes.init(year, month, day, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int month_i = monthOfYear + 1;
Log.e("selected month:", Integer.toString(month_i));
//Add whatever you need to handle Date changes
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int daySpinnerId = Resources.getSystem().getIdentifier("day", "id", "android");
if (daySpinnerId != 0) {
View daySpinner = dp_mes.findViewById(daySpinnerId);
if (daySpinner != null) {
daySpinner.setVisibility(View.GONE);
}
}
int monthSpinnerId = Resources.getSystem().getIdentifier("month", "id", "android");
if (monthSpinnerId != 0) {
View monthSpinner = dp_mes.findViewById(monthSpinnerId);
if (monthSpinner != null) {
monthSpinner.setVisibility(View.VISIBLE);
}
}
int yearSpinnerId = Resources.getSystem().getIdentifier("year", "id", "android");
if (yearSpinnerId != 0) {
View yearSpinner = dp_mes.findViewById(yearSpinnerId);
if (yearSpinner != null) {
yearSpinner.setVisibility(View.GONE);
}
}
} else { //Older SDK versions
Field f[] = dp_mes.getClass().getDeclaredFields();
for (Field field : f) {
if (field.getName().equals("mDayPicker") || field.getName().equals("mDaySpinner")) {
field.setAccessible(true);
Object dayPicker = null;
try {
dayPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) dayPicker).setVisibility(View.GONE);
}
if (field.getName().equals("mMonthPicker") || field.getName().equals("mMonthSpinner")) {
field.setAccessible(true);
Object monthPicker = null;
try {
monthPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) monthPicker).setVisibility(View.VISIBLE);
}
if (field.getName().equals("mYearPicker") || field.getName().equals("mYearSpinner")) {
field.setAccessible(true);
Object yearPicker = null;
try {
yearPicker = field.get(dp_mes);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
((View) yearPicker).setVisibility(View.GONE);
}
}
}
}
}
Layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.calendarviewtest.MainActivity">
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker2" />
</RelativeLayout>
Is there anything I am doing wrong?
So, I have scoured the interwebs and I cannot find a solution for this based on other people's experiences, so I am posting this issue. (Please note that this is my 1st android app experience and I am debugging / updating an existing app.)
When I implement my custom NotesListAdapter (extends BaseAdapter) on the ListView, mListNotesView (mListNotesView.setAdapter(this)), and load the data into the ArrayList mNoteList, the getView function is not being called. Also, I found that mListNotesView.setBackgroundResource is not chaning the background of the control, either. I have a similar implementation on a previous activity that works exactly correct. When I copied over the class and changed it to handle my ArrayList, it broke. I have getCount returning the ArrayList size(), which is not 0, and getItemId returns position. I have a feeling it may be my XML or my setup because it's acting like the ListView is not visible. I am perplexed. How do I get the ListView to show? Anything inside of the getView has not been reached so it may be buggy.
ViewTicketOrderActivity (Some parts ommitted for size)
public class ViewTicketOrderActivity extends Activity {
MySQLDatabase myDataBase;
Ticket mTicket;
public ArrayList<Notes> mNotes = new ArrayList<Notes>();
String mErrorString;
Button mAddUpdateButton;
Button mAcceptButton;
//Button mViewNotesButton;
NotesListAdapter mNotesListAdapter;
static final int ERROR_DIALOG = 0;
static final int SUCCESS_DIALOG = 1;
static final int COMPLETED_DIALOG = 2;
static final int RESTART_DIALOG = 3;
static final int LOADING = 0;
static final int LOAD_ERROR = 1;
static final int LOADED = 4;
static final String TICKET_EXTRA = "ticket_extra";
static final String TAG = "ViewTicketOrderActivity";
private static final boolean gDebugLog = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewticketorder);
Activity context = this;
String theTitle = "Sundance Ticket Order";
theTitle += (MySQLDatabase.TESTING == true) ? " (DEV SERVER)" : " (LIVE)";
setTitle(theTitle);
myDataBase = MySQLDatabase.getMySQLDatabase(this);
if (gDebugLog) {
DebugLogger.logString(TAG, ".onCreate");
}
mNotesListAdapter = new NotesListAdapter(context, R.id.note_list);
Log.d(this.toString(),this.mNotesListAdapter.toString());
}
private class NotesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Notes> mNoteList;
private ListView mListNotesView;
private Activity mActivity;
int mState = LOADING;
String mErrorMessage;
private NotesListAdapter(Activity context, int listViewID) {
mActivity = context;
mNoteList = new ArrayList<Notes>();
mInflater = LayoutInflater.from(context);
mListNotesView = (ListView)context.findViewById(listViewID);
mListNotesView.setBackgroundResource(R.color.emergency_red);
mListNotesView.setAdapter(this);
Log.d(mListNotesView.toString(), String.valueOf(mListNotesView.getCount()));
this.notifyDataSetChanged();
//mListNotesView.setVisibility(View.VISIBLE);
}
void setLoading()
{
mState = LOADING;
this.notifyDataSetChanged();
}
void setLoadError(String errorString)
{
mState = LOAD_ERROR;
mErrorMessage = errorString;
this.notifyDataSetChanged();
}
void setNoteList(ArrayList<Notes> inNotes)
{
mState = LOADED;
mNoteList.clear();
mNoteList.addAll(inNotes);
Log.d("SetNoteList", "TRUE " + inNotes);
//mNoteList = mNotes;
this.notifyDataSetChanged();
}
/**
* Use the array index as a unique id.
*
* #see android.widget.ListAdapter#getItemId(int)
*/
#Override
public long getItemId(int position) {
return position;
}
public int getCount(){
if (mState == LOADED) {
Log.d("getCount",String.valueOf(mNoteList.size()));
return mNoteList.size();
} else {
return 0;
}
}
/**
* Make a view to hold each row.
*
* #see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
Log.d("getView",this.toString());
if (mState == LOADED) {
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there
// is no need
// to reinflate it. We only inflate a new View when the
// convertView supplied
// by ListView is null.
Notes note = this.getItem(position);
if (convertView == null) {
/*if (ticket.emergency())
{
convertView = mInflater.inflate(R.layout.emergency_ticket_list_item_opt,
null);
}
else
{
convertView = mInflater.inflate(R.layout.ticket_list_item,
null);
}*/
convertView = mInflater.inflate(R.layout.noteslist_item,
null);
// Creates a ViewHolder and store references to the two
// children views
// we want to bind data to.
holder = new ViewHolder();
holder.noteText = (TextView) convertView
.findViewById(R.id.text_note);
holder.dateText = (TextView) convertView
.findViewById(R.id.text_note_date);
holder.createByText = (TextView) convertView
.findViewById(R.id.text_note_by);
holder.createByIDText = (TextView) convertView
.findViewById(R.id.text_note_by_id);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the
// TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.noteText.setText(note.note());
holder.dateText.setText(note.date());
holder.createByText.setText(note.createBy());
holder.createByIDText.setText(note.employeeID());
if(!mTicket.employeeID().equals(note.employeeID())){
convertView.setBackgroundResource(R.drawable.solid_purple);
}
} else if (mState == LOADING ) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.loading_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Loading tickets");
} else if (mState == LOAD_ERROR) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.load_error_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Error loading tickets");
String errorString = mErrorMessage != null ? mErrorMessage : "";
TextView errorText = (TextView)convertView.findViewById(R.id.errorText);
errorText.setText(errorString);
}
return convertView;
}
class ViewHolder {
TextView noteText;
TextView dateText;
TextView createByText;
TextView createByIDText;
}
//#Override
/*public int getCount() {
*//*if (mState == LOADED) {
*//*
Log.d("getCount mState " + mState,String.valueOf(mNoteList.size())+", "+String.valueOf(mNotes.size()));
return mNoteList.size();
*//*} else {
Log.d("getCount mState " + mState,"0");
return 0;
}*//*
}*/
#Override
public Notes getItem(int position) {
Log.d("getItem",mNoteList.get(position).toString());
return mNoteList.get(position);
}
#Override
public int getItemViewType (int position) {
int result = mState;
Log.d("getItemId",String.valueOf(position));
return result;
}
#Override
public int getViewTypeCount ()
{
return 4;
}
}
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
mTicket = (Ticket)extras.getSerializable(TICKET_EXTRA);
}
else
{
mTicket = new Ticket();
}
if (mTicket.emergency())
{
setContentView(R.layout.view_emergency_ticketorder);
}
else
{
setContentView(R.layout.viewticketorder);
}
if (gDebugLog)
{
DebugLogger.logString(TAG, ".onResume mTicket " + mTicket);
}
TicketCheckService.clearNotificationForNewTicket(mTicket);
new GetTicketTask().execute();
new GetNotesTask().execute();
updateDisplayedTicket();
}
private void updateDisplayedTicket() {
mAddUpdateButton = (Button)findViewById(R.id.addUpdateButton);
mAcceptButton = (Button)findViewById(R.id.acceptButton);
//mViewNotesButton = (Button)findViewById(R.id.viewNotesButton);
String ticketStatus = myDataBase.getDescriptionStringForStatusString(mTicket.status());
if(ticketStatus == "Job Rejected") {
mAddUpdateButton.setText("Restart Job");
} else {
mAddUpdateButton.setText("Add Update");
}
if(ticketStatus == "Requested") {
mAcceptButton.setText("Accept");
} else if(ticketStatus != "Requested") {
mAcceptButton.setText("Back");
}
//mViewNotesButton.setText(R.string.viewNotes);
TextView idText = (TextView)findViewById(R.id.textTicketID);
idText.setText(mTicket.id());
//TextView descriptionText = (TextView)findViewById(R.id.textDescription);
//descriptionText.setText(mTicket.description());
TextView titleText = (TextView)findViewById(R.id.textTitle);
titleText.setText(mTicket.title());
TextView storeIDText = (TextView)findViewById(R.id.textStoreID);
storeIDText.setText(mTicket.store());
String formatPhone;
TextView storePhoneText = (TextView)findViewById(R.id.textStorePhone);
if(mTicket.phoneNo().isEmpty()){
formatPhone = "NO PHONE NO.";
} else {
storePhoneText = (TextView) findViewById(R.id.textStorePhone);
formatPhone = mTicket.phoneNo().replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
storePhoneText.setOnClickListener(new CallClickListener(mTicket.phoneNo()));
}
storePhoneText.setText(formatPhone);
TextView categoryText = (TextView)findViewById(R.id.textCategory);
String categoryDescription = MySQLDatabase.getDescriptionStringForCategoryString(mTicket.category());
categoryText.setText(categoryDescription);
if(ticketStatus == "Completed Pending") {
showDialog(COMPLETED_DIALOG);
}
}
public void onClickAccept(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAcceptButton.getText() =="Accept") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new AcceptTicketTask().execute();
} else {
finish();
}
}
public void onClickAddUpdate(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAddUpdateButton.getText() =="Add Update") {
Intent i = new Intent(this, UpdateTicketActivity.class);
i.putExtra(UpdateTicketActivity.TICKET_EXTRA, mTicket);
startActivity(i);
} else if(mAddUpdateButton.getText() =="Restart Job") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new RestartTicketTask().execute();
}
}
private class AcceptTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "1", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString) {
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(SUCCESS_DIALOG);
mAcceptButton.setText("Back");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class RestartTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "7", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString)
{
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(RESTART_DIALOG);
mAcceptButton.setText("Done");
mAddUpdateButton.setText("Add Update");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class GetTicketTask extends AsyncTask<Void, Integer, Ticket>
{
String mError = null;
protected Ticket doInBackground(Void... parent) {
Ticket result = null;
try {
result = myDataBase.getTicketWithID(mTicket.id(), mTicket.employeeID());
} catch (IOException e) {
// TODO Auto-generated catch block
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Ticket result)
{
if (null != result) {
mTicket = result;
} else {
setLoadError(mError);
}
}
}
private class GetNotesTask extends AsyncTask<Void, Integer, ArrayList<Notes>> {
String mError = null;
protected ArrayList<Notes> doInBackground(Void... parent) {
ArrayList<Notes> result = new ArrayList<Notes>();
try {
result = myDataBase.getTicketNotes(mTicket.id());
} catch (IOException e) {
// TODO Auto-generated catch block
myDataBase.debugLog("Error caught" + e);
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ArrayList<Notes> result) {
if (null != result) {
Log.d("Result", result.toString());
mNotes = result;
} else {
Log.d("SetNoteList","FALSE");
mNotesListAdapter.setLoadError(mError);
}
}
}
private void updateDisplayedNotes(){
ArrayList<Notes> newNotes = mNotes;
if(newNotes != null) {
mNotesListAdapter.setNoteList(newNotes);
}
}
/*private class updateDisplayedNotes extends AsyncTask<Void, Integer, ArrayList<Notes>> {
public ArrayList<Notes> newNotes = new ArrayList<Notes>();
public updateDisplayedNotes(){
super();
Log.d(this.toString(), "Updating");
}
protected ArrayList<Notes> doInBackground(Void... parent) {
Log.d(this.toString(), "Background Task");
for (Notes note : mNotes) {
Log.d(this.toString(),note.toString());
if(note != null) {
Log.d(this.toString(), "Note Added");
newNotes.add(note);
}
}
return newNotes;
}
protected void onPostExecute(ArrayList<Notes> newNotes)
{
if(newNotes != null) {
mNotes.clear();
mNotes.addAll(newNotes);
mNotesListAdapter.setNoteList(mNotes);
}
}
}*/
void setLoadError(String error) {
setContentView(R.layout.load_error_view);
TextView messageText = (TextView)findViewById(R.id.message);
messageText.setText("Error loading ticket");
String errorString = error != null ? error : "";
TextView errorText = (TextView)findViewById(R.id.errorText);
errorText.setText(errorString);
finish();
}
}
viewticketorder.xml (where note_list is)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context=".ViewTicketOrderActivity"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="#string/loadingTicket"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white_color"
android:textSize="20dp"
android:textIsSelectable="true"
android:background="#drawable/title_transparent_bg"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:text="#string/ticketID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textTicketID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:text="#string/storeID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textStoreID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textStorePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:paddingTop="2dp"
android:text="#string/category"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white_color"
android:focusable="true"
android:textIsSelectable="true"/>
</LinearLayout>
<ListView
android:id="#+id/note_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:divider="#drawable/ticket_item_divider"
android:dividerHeight="1dp"
tools:ignore="NestedWeights"
android:choiceMode="singleChoice"
android:clickable="true"
android:background="#drawable/title_transparent_bg">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/acceptButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:onClick="onClickAccept" />
<Button
android:id="#+id/addUpdateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:onClick="onClickAddUpdate" />
</LinearLayout>
</LinearLayout>
notelist_item.xml (inflator)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text_note_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFFFF"
android:orientation="vertical"
>
<TextView
android:id="#+id/text_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/text_item_color"
android:textSize="#dimen/big_text_item_size" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight=".70"
>
<TextView
android:id="#+id/text_note_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
</LinearLayout>
</LinearLayout>
I'm going to recommend you reorganize your code. Here are some general tips:
1) Keep your views like ListView in the Activity class. Don't try to inflate the view in your adapter class. So in your activity's onCreate() after setContentView() you should have something like:
ListView listView = (ListView) findViewById(R.id.listView);
2) Next you need to get the data that will be shown in the listview and store it in a list. I didn't see in your code where the data comes from, but let's just say it comes from a database. You should create something like an ArrayList and store the data that you want to show in the ListView in the ArrayList
3) Next you need to create an adapter and pass the list of data into the adapter.
4) Once this has been done the ListView now has an adapter that will supply data to it. If you've done everything correctly then the system will eventually call getView() automatically and your code inside that should run and render the view.
Not an exact solution, but hopefully this explanation will help you figure it out.
I really need help here. I have project which call MyHeartRate, I downloaded the source code of heart rate project at Github. So I try to run that source code and there is no error. In the interface layout, it display the "camera". Example, when you open your camera then you will see the screen focus on what area that you want to take the picture. So my problem is, I want to remove that "camera" in my layout. I need to know which code need to be delete so then the "camera" not in my layout.
here's my code
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<LinearLayout android:id="#+id/top"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp">
<TextView android:id="#+id/text"
android:text="#string/default_text"
android:textSize="32dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.jwetherell.heart_rate_monitor.HeartbeatView android:id="#+id/image"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.jwetherell.heart_rate_monitor.HeartbeatView>
</RelativeLayout>
</LinearLayout>
<SurfaceView android:id="#+id/preview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="0dp">
</SurfaceView>
java file(HeartRateMonitor)
public class HeartRateMonitor extends Activity {
private static final String TAG = "HeartRateMonitor";
private static final AtomicBoolean processing = new AtomicBoolean(false);
private static SurfaceView preview = null;
private static SurfaceHolder previewHolder = null;
private static Camera camera = null;
private static View image = null;
private static TextView text = null;
private static WakeLock wakeLock = null;
private static int averageIndex = 0;
private static final int averageArraySize = 4;
private static final int[] averageArray = new int[averageArraySize];
public static enum TYPE {
GREEN, RED
};
private static TYPE currentType = TYPE.GREEN;
public static TYPE getCurrent() {
return currentType;
}
private static int beatsIndex = 0;
private static final int beatsArraySize = 3;
private static final int[] beatsArray = new int[beatsArraySize];
private static double beats = 0;
private static long startTime = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
image = findViewById(R.id.image);
text = (TextView) findViewById(R.id.text);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
camera = Camera.open();
startTime = System.currentTimeMillis();
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
private static PreviewCallback previewCallback = new PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera cam) {
if (data == null) throw new NullPointerException();
Camera.Size size = cam.getParameters().getPreviewSize();
if (size == null) throw new NullPointerException();
if (!processing.compareAndSet(false, true)) return;
int width = size.width;
int height = size.height;
int imgAvg = ImageProcessing.decodeYUV420SPtoRedAvg(data.clone(), height, width);
// Log.i(TAG, "imgAvg="+imgAvg);
if (imgAvg == 0 || imgAvg == 255) {
processing.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < averageArray.length; i++) {
if (averageArray[i] > 0) {
averageArrayAvg += averageArray[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
// Log.d(TAG, "BEAT!! beats="+beats);
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (averageIndex == averageArraySize) averageIndex = 0;
averageArray[averageIndex] = imgAvg;
averageIndex++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
image.postInvalidate();
}
long endTime = System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= 10) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
processing.set(false);
return;
}
// Log.d(TAG,
// "totalTimeInSecs="+totalTimeInSecs+" beats="+beats);
if (beatsIndex == beatsArraySize) beatsIndex = 0;
beatsArray[beatsIndex] = dpm;
beatsIndex++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < beatsArray.length; i++) {
if (beatsArray[i] > 0) {
beatsArrayAvg += beatsArray[i];
beatsArrayCnt++;
}
}
int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
text.setText(String.valueOf(beatsAvg));
startTime = System.currentTimeMillis();
beats = 0;
}
processing.set(false);
}
};
private static SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
camera.setPreviewCallback(previewCallback);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
Camera.Size size = getSmallestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
}
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Ignore
}
};
private static Camera.Size getSmallestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea < resultArea) result = size;
}
}
}
return result;
}
}
tq,
faizal
I found the answer. just comment this code
//preview = (SurfaceView) findViewById(R.id.preview);
//previewHolder = preview.getHolder();
//previewHolder.addCallback(surfaceCallback);
//previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
done.