Get integer value from edittext And Access value on Button - java

I want to get int Value from Edittext and then access that value On Button. But When I Access On Button It Show Error Remove "Final" modifier of "val". When I remove it then on button listener mViewPager.setCurrentItem(val); Show error That Change modifier of 'val'to Final.
Here Is my Code
bt_Goto =(Button)findViewById(R.id.btn_goto);
bt_next =(Button)findViewById(R.id.btn_next);
bt_Prev =(Button)findViewById(R.id.btn_prev);
ed_text =(EditText)findViewById(R.id.editText1);
final int val=-1;
if(ed_text.getText().toString().length() > 0){
val = Integer.parseInt( ed_text.getText().toString() );
}
// String str = ed_text.getText().toString().trim();
mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
mViewPager.setCurrentItem(0);
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(val);
}
});
Full Code:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.app.Activity;
public class MainActivity extends Activity {
Button bt_next,bt_Prev,bt_Goto;
EditText ed_text;
ImageView iv;
ExtendedViewPager mViewPager;
AdView adView;
int val=-1;
private StartAppAd startAppAd = new StartAppAd(this);
private static final String AD_UNIT_ID = "ca-app-pub-3785804349839269/3077204438";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAppSDK.init(this, "101607288", "201235812", true);
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
bt_Goto =(Button)findViewById(R.id.btn_goto);
bt_next =(Button)findViewById(R.id.btn_next);
bt_Prev =(Button)findViewById(R.id.btn_prev);
ed_text =(EditText)findViewById(R.id.editText1);
if(ed_text.getText().toString().length() > 0){
val = Integer.parseInt( ed_text.getText().toString() );
}
// String str = ed_text.getText().toString().trim();
mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
mViewPager.setCurrentItem(0);
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(val);
}
});
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images =
{R.raw.a0002,R.raw.a0003,R.raw.a0004,R.raw.a0005,R.raw.a0006,R.raw.a0007,R.raw.a0008,R.raw.a0009,R.raw.a0010,
R.raw.a0011,R.raw.a0012,R.raw.a0013,R.raw.a0014,R.raw.a0015,R.raw.a0016,R.raw.a0017,R.raw.a0018,R.raw.a0019,R.raw.a0020,
R.raw.a0021,R.raw.a0022,R.raw.a0023,R.raw.a0024,R.raw.a0025,R.raw.a0026,R.raw.a0027,R.raw.a0028,R.raw.a0029,R.raw.a0030,
R.raw.a0031,R.raw.a0032,R.raw.a0033,R.raw.a0034,R.raw.a0035,R.raw.a0036,R.raw.a0037,R.raw.a0038,R.raw.a0039,R.raw.a0040,
R.raw.a0041,R.raw.a0042,R.raw.a0043,R.raw.a0044,R.raw.a0045,R.raw.a0046,R.raw.a0047,R.raw.a0048,R.raw.a0049,R.raw.a0050,
R.raw.a0051,R.raw.a0052,R.raw.a0053,R.raw.a0054,R.raw.a0055,R.raw.a0056,R.raw.a0057,R.raw.a0058,R.raw.a0059,R.raw.a0060,
R.raw.a0061,R.raw.a0062,R.raw.a0063,R.raw.a0064,R.raw.a0065,R.raw.a0066,R.raw.a0067,R.raw.a0068,R.raw.a0069,R.raw.a0070,
R.raw.a0071,R.raw.a0072,R.raw.a0073,R.raw.a0074,R.raw.a0075,R.raw.a0076,R.raw.a0077,R.raw.a0078,R.raw.a0079,R.raw.a0080,
R.raw.a0081,R.raw.a0082,R.raw.a0083,R.raw.a0084,R.raw.a0085,R.raw.a0086,R.raw.a0087,R.raw.a0088,R.raw.a0089,R.raw.a0090,
R.raw.a0091,R.raw.a0092,R.raw.a0093,R.raw.a0094,R.raw.a0095,R.raw.a0096,R.raw.a0097,R.raw.a0098,R.raw.a0099,R.raw.a0100,
R.raw.a0101,R.raw.a0102,R.raw.a0103,R.raw.a0104,R.raw.a0105,R.raw.a0106,R.raw.a0107,R.raw.a0108,R.raw.a0109,R.raw.a0110,
R.raw.a0111,R.raw.a0112,R.raw.a0113,R.raw.a0114,R.raw.a0115,R.raw.a0116,R.raw.a0117,R.raw.a0118,R.raw.a0119,R.raw.a0120,
R.raw.a0121,R.raw.a0122,R.raw.a0123,R.raw.a0124,R.raw.a0125,R.raw.a0126,R.raw.a0127,R.raw.a0128,R.raw.a0129,R.raw.a0130,
R.raw.a0131,R.raw.a0132,R.raw.a0133,R.raw.a0134,R.raw.a0135,R.raw.a0136,R.raw.a0137,R.raw.a0138,R.raw.a0139,R.raw.a0140,
R.raw.a0141,R.raw.a0142,R.raw.a0143,R.raw.a0144,R.raw.a0145,R.raw.a0146,R.raw.a0147,R.raw.a0148,R.raw.a0149,R.raw.a0150,
R.raw.a0151,R.raw.a0152,R.raw.a0153,R.raw.a0154,R.raw.a0155,R.raw.a0156,R.raw.a0157,R.raw.a0158,R.raw.a0159,R.raw.a0160,
R.raw.a0161,R.raw.a0162,R.raw.a0163,R.raw.a0164,R.raw.a0165,R.raw.a0166,R.raw.a0167,R.raw.a0168,R.raw.a0169,R.raw.a0170,
R.raw.a0171,R.raw.a0172,R.raw.a0173,R.raw.a0174,R.raw.a0175,R.raw.a0176,R.raw.a0177,R.raw.a0178,R.raw.a0179,R.raw.a0180,
R.raw.a0181,R.raw.a0182,R.raw.a0183,R.raw.a0184,R.raw.a0185,R.raw.a0186,R.raw.a0187,R.raw.a0188,R.raw.a0189,R.raw.a0190,
R.raw.a0191,R.raw.a0192,R.raw.a0193,R.raw.a0194,R.raw.a0195,R.raw.a0196,R.raw.a0197,R.raw.a0198,R.raw.a0199,R.raw.a0200,
R.raw.a0201,R.raw.a0202,R.raw.a0203,R.raw.a0204,R.raw.a0205,R.raw.a0206,R.raw.a0207,R.raw.a0208,R.raw.a0209,R.raw.a0210,
R.raw.a0211,R.raw.a0212,R.raw.a0213,R.raw.a0214,R.raw.a0215,R.raw.a0216,R.raw.a0217,R.raw.a0218,R.raw.a0219,R.raw.a0220,
R.raw.a0221,R.raw.a0222,R.raw.a0223,R.raw.a0224,R.raw.a0225,R.raw.a0226,R.raw.a0227,R.raw.a0228,R.raw.a0229,R.raw.a0230,
R.raw.a0231,R.raw.a0232,R.raw.a0233,R.raw.a0234,R.raw.a0235,R.raw.a0236,R.raw.a0237,R.raw.a0238,R.raw.a0239,R.raw.a0240,
R.raw.a0241,R.raw.a0242,R.raw.a0343,R.raw.a0344,R.raw.a0245,R.raw.a0246,R.raw.a0347,R.raw.a0248,R.raw.a0249,R.raw.a0250,
R.raw.a0251,R.raw.a0252,R.raw.a0253,R.raw.a0254,R.raw.a0255,R.raw.a0256,R.raw.a0257,R.raw.a0258,R.raw.a0259,R.raw.a0260,
R.raw.a0261,R.raw.a0262,R.raw.a0263,R.raw.a0264,R.raw.a0265,R.raw.a0266,R.raw.a0267,R.raw.a0268,R.raw.a0269,R.raw.a0270,
R.raw.a0271,R.raw.a0272,R.raw.a0273,R.raw.a0274,R.raw.a0275,R.raw.a0276,R.raw.a0277,R.raw.a0278,R.raw.a0279,R.raw.a0280,
R.raw.a0281,R.raw.a0282,R.raw.a0283,R.raw.a0284,R.raw.a0285,R.raw.a0286,R.raw.a0287,R.raw.a0288,R.raw.a0289,R.raw.a0290,
R.raw.a0291,R.raw.a0292,R.raw.a0293,R.raw.a0294,R.raw.a0295,R.raw.a0296,R.raw.a0297,R.raw.a0298,R.raw.a0299,R.raw.a0300,
R.raw.a0301,R.raw.a0302,R.raw.a0303,R.raw.a0304,R.raw.a0305,R.raw.a0306,R.raw.a0307,R.raw.a0308,R.raw.a0309,R.raw.a0310,
R.raw.a0311,R.raw.a0312,R.raw.a0313,R.raw.a0314,R.raw.a0315,R.raw.a0316,R.raw.a0317,R.raw.a0318,R.raw.a0319,R.raw.a0320,
R.raw.a0321,R.raw.a0322,R.raw.a0323,R.raw.a0324,R.raw.a0325,R.raw.a0326,R.raw.a0327,R.raw.a0328,R.raw.a0329,R.raw.a0330,
R.raw.a0331,R.raw.a0332,R.raw.a0333,R.raw.a0334,R.raw.a0335,R.raw.a0336,R.raw.a0337,R.raw.a0338,R.raw.a0339,R.raw.a0340,
R.raw.a0341,R.raw.a0342,R.raw.a0343,R.raw.a0344,R.raw.a0345,R.raw.a0346,R.raw.a0347,R.raw.a0348,R.raw.a0349,R.raw.a0350,
R.raw.a0351,R.raw.a0352,R.raw.a0353,R.raw.a0354,R.raw.a0355,R.raw.a0356,R.raw.a0357,R.raw.a0358,R.raw.a0359,R.raw.a0360,
R.raw.a0361,R.raw.a0362,R.raw.a0363,R.raw.a0364};
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}

Declare the ed_text and mViewPager in your onCreate like this
final EditText ed_text =(EditText)findViewById(R.id.editText1);
final ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
and now you can access the ed_text value in the bt_Goto click listener like this
bt_Goto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.getText().toString().length() > 0){
mViewPager.setCurrentItem(Integer.parseInt( ed_text.getText().toString()));
}
}
});

Remove the final keyword from your int
final int val=-1;
^^^^ remove that
Besides that, declare it as a class field so you can access it in the listener scope.

Declare your int val variable at class level
And when it come to method initialise it with -1.
Hope fully it ll work.

You can achieve this using temp variable.
int value_temp = -1;
if(ed_text.getText().toString().length() > 0){
value_temp = Integer.parseInt( ed_text.getText().toString() );
}
final int value = value_temp;
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(value);
}
});

Related

Click on one card view affected another card view value

When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.

Recyclerview change item color outside adapter

Currently I'm trying figure out how to change an RecyclerView item color outside adapter. I'm just manipulating the position, and works fine! But I must swipe the page to color update, and I don't know what I should do to fix this problem.
Check my code:
MainActivity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
player_prev = findViewById(R.id.prev);
player_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((currentPos-1) > 0) {
killMediaPlayer();
initAudio(getApplicationContext(),
RecyclerViewAdapter.mData.get(currentPos - 1).getURL());
currentPos -= 1;
RecyclerViewAdapter.OldselectedPos = RecyclerViewAdapter.selectedPos;
RecyclerViewAdapter.selectedPos = currentPos;
adapter.notifyDataSetChanged();
}
});
...
}
RecyclerViewAdapter.java
package etes.xdda.music;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
MainActivity activity;
static List<mList> mData;
Dialog myDialog;
public static int selectedPos = RecyclerView.NO_POSITION;
public static int OldselectedPos = RecyclerView.NO_POSITION;
private LinearLayout menu_dialog, menu_dialog2;
public static TextView song_detail;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
#Override
public void onClick(View view) { }
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(activity);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
OldselectedPos = selectedPos;
selectedPos = vHolder.getAdapterPosition();
notifyItemChanged(selectedPos);
notifyItemChanged(OldselectedPos);
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
menu_dialog2 = v.getRootView().findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(v.VISIBLE);
song_detail = v.getRootView().findViewById(R.id.song_detail);
song_detail.setVisibility(v.VISIBLE);
String newName;
newName = mData.get(vHolder.getAdapterPosition()).getName();
if (newName.length() > 42) {
newName = newName.substring(0, 38) + "...";
}
song_detail.setText(newName);
activity.killMediaPlayer();
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,205);
activity.updateNotificationBar("mzPlay", mData.get(vHolder.getAdapterPosition()).getName());
MainActivity.currentPos = vHolder.getAdapterPosition();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
//Toast.makeText(activity, String.valueOf(holder), Toast.LENGTH_LONG).show();
if(selectedPos == position){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = itemView.findViewById(R.id.name_list);
tv_author = itemView.findViewById(R.id.author_list);
img = itemView.findViewById(R.id.img_music);
}
}
}
Video: https://ntcdn.stream/20181009_2342010.mp4
The problem is: I must swipe the page to item colors be updated, how can I update the colors without page swipe?
Storing andoid classes in static variables is really a very bad practice. You should interact with your adapter the regular way, using a non static field, for example:
//This will go in your onCreate() for example
MyAdapter adapter = new MyAdapter(parameters);
...
adapter.highligtedItemPosition = 10;
adapter.notifyItemChanged(10);
and later in your onBindViewHolder() react according to what background you want set:
if(position == highligtedItemPosition ){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
in this example you must add an integer field:
int highligtedItemPosition;
to your adapter to store the position of the item you want to change the color of.
UPDATE:
You are not calling notifyItemChange() or notifyDataSetChanged() from your activity, so the adapter needs to "wait" for the scrolling action to "see" the changes. You should call notifyItemChange() or notifyDataSetChanged() from your player_prev's OnClickListener instead. So the adapter will reflect the changes immediately.

Can't resolve setOnItemSelectedListener

My goal is to make items from spinner list to change background color of main_activity.
But I can't get working setOnItemSelectedListener for some reason.
Spinner works fine, toast also, but setOnItemSelectedListener is getting error: "cant resolve the symbol..."
Couldn't find any help online that was applicable to my case.
Please see code below:
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Button;
import android.widget.ToggleButton;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
private TextView tekst1;
private int ile = 1;
private Button klawisz1;
private ToggleButton onOff;
private Spinner spinner1;
public void setActivityBackgroundColor(int color) {
View view = this.getWindow().getDecorView();
view.setBackgroundColor(color);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tekst1 = (TextView) findViewById(R.id.tekst);
klawisz1 = (Button) findViewById(R.id.button);
onOff = (ToggleButton) findViewById(R.id.toggleButton);
spinner1 = (Spinner) findViewById(R.id.spinner);
spinner1.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
spinner1.setOnItemSelectedListener(this);
List<String> colors = new ArrayList<String>();
colors.add("White");
colors.add("Yellow");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colors);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
onOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((++ile%2)==0) {
spinner1.setVisibility(View.VISIBLE);
}
else{
spinner1.setVisibility(View.GONE);
}
}
});
}
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
//setActivityBackgroundColor(Color.YELLOW);
String item = parent.getItemAtPosition(position).toString();
if(selectedItem.equals("White"))
{
setActivityBackgroundColor(Color.WHITE);
}
else if(selectedItem.equals("Yellow"))
{
setActivityBackgroundColor(Color.YELLOW);
}
// Showing selected spinner item
//Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public void buttonOnClick(View view) {
if ((++ile%2)==0){
tekst1.setText(new Date().toString());
klawisz1.setBackgroundColor(Color.RED);
}
else
{
tekst1.setText("Next click - TIME");
klawisz1.setBackgroundColor(Color.GREEN);
}
}
You have an extra } before the setOnItemSelectedListener() call and the code is outside of the onCreate() method. Code like spinner1.setOnItemSelectedListener(...) needs to be inside a method.
Try below code for your Spinner:
mTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Do your stuff at item selection time.
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Intentionally kept blank
}
});
It's becoz you have set setOnItemSelectedListener two times for spinner 1
\\ spinner1.setOnItemSelectedListener((AdapterView.OnItemSelectedListener)
this); \\not required
spinner1.setOnItemSelectedListener(this);
you should set only 1 setOnItemSelectedListener for spinner1
This code worked fine for me.Try it...
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
List<String> colors;
private TextView tekst1;
private int ile = 1;
private Button klawisz1;
private ToggleButton onOff;
private Spinner spinner1;
public void setActivityBackgroundColor(int color) {
View view = this.getWindow().getDecorView();
view.setBackgroundColor(color);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tekst1 = (TextView) findViewById(R.id.tekst);
klawisz1 = (Button) findViewById(R.id.button);
onOff = (ToggleButton) findViewById(R.id.toggleButton);
spinner1 = (Spinner) findViewById(R.id.spinner);
klawisz1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonOnClick(view);
}
});
spinner1.setOnItemSelectedListener(this);
colors = new ArrayList<String>();
colors.add("White");
colors.add("Yellow");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colors);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
onOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((++ile % 2) == 0) {
spinner1.setVisibility(View.VISIBLE);
} else {
spinner1.setVisibility(View.GONE);
}
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
//setActivityBackgroundColor(Color.YELLOW);
String item = colors.get(position);
if (item.equals("White")) {
setActivityBackgroundColor(Color.WHITE);
} else if (item.equals("Yellow")) {
setActivityBackgroundColor(Color.YELLOW);
}
// Showing selected spinner item
//Toast.makeText(parent.getContext(), "Selected: " + item,
//Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void buttonOnClick(View view) {
if ((++ile % 2) == 0) {
tekst1.setText(new Date().toString());
klawisz1.setBackgroundColor(Color.RED);
} else {
tekst1.setText("Next click - TIME");
klawisz1.setBackgroundColor(Color.GREEN);
}
}
}

TextView does not show log

Okay I am new with android and i have been following a course but there are somethings that i don't understand.
This is LifeCycleT activity.
package com.example.killtheviolence.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class LifeCycleT extends Activity {
StringBuilder builde = new StringBuilder();
TextView textview;
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append( builde.toString() );
builde.append("\n");
textview.setText(builde.toString());
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText(builde.toString());
setContentView(textview);
}
protected void onResume() {
super.onResume();
log("resume");
}
protected void onPause() {
super.onPause();
log("paused");
if(isFinishing()) {
log("death");
}
}
}
Where this came from? From a ListView.
package com.example.killtheviolence.myapplication;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
String prueva[] = {"LifeCycleT","item2","item3","item4",
"item5 ", "item6 "};
public void onCreate(Bundle savedInstanceSate){
super.onCreate(savedInstanceSate);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, prueva));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String gate = prueva[position];
try {
Class<?> inst;
inst = Class.forName("com.example.killtheviolence.myapplication." + gate);
Intent intent = new Intent(this, inst);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
That's the main activity.
What I want to do show in the TextView the Log.d in the screen but I get an error:
Unable to resume activity
{com.example.killtheviolence.myapplication/com.example.killtheviolence.myapplication.LifeCycleT}:
java.lang.NullPointerException
So I looked for a reason (meaning for a NullPointerException and it was that
I used TextView before initializing on the line textview.setText(builde.toString());
What I did was create an instance of TextView in log function.
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append(builde.toString());
builde.append("\n");
TextView textview = new TextView(this);
textview.setText(builde.toString());
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText(builde.toString());
setContentView(textview);
}
Why have I to create two instances of TextView? And why have I to setText twice? Why doesn't it show anything in the TextView? (only shows when i wrote a "string" in the arguments of setText.)
fix your onCreate to set the field parameter not a local parameter:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
textview = new TextView(this); // << This used to be a local var, thats why NPE
textview.setText(builde.toString());
setContentView(textview);
}
Then remove the 2nd creation of the TextView from log
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append("\n");
builde.append(text);
textview.setText(builde.toString());
}
Also notice that I changed your StringBuilder to append the text that you pass as a parameter into your log method

How can i get the 3 textview from recyclerview and pass it to dialogbox

Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.

Categories

Resources