I want to get TextView reference in class but i get exceptions - java

Here is the code for my mainActivity.java file
I am trying to access the reference of textview in class MyGestureListener but i am unable to do this because every time my application unfortunately stopped on scroll gesture.
here is my code
This is my main class
public class MainActivity extends AppCompatActivity {
TextView myText;
Button myButton;
private GestureDetectorCompat mDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText = (TextView)findViewById(R.id.myText);
myButton = (Button)findViewById(R.id.myButton);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
myButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
myText.setText("I am clicked from button");
}
});
}
public TextView getTextView()
{
TextView txtView = (TextView)findViewById(R.id.myText);
return txtView;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
}
This is my user defined class
class extends GestureDetector.SimpleOnGestureListener {
private TextView myText;
MainActivity m;
public MyGestureListener(){
m = new MainActivity();
}
//MainActivity m = new MainActivity();
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
myText.setText("Scroll ho v ja hun");
return true;
}
}

You must not create any Activity objects yourself, as you do in the MyGestureListener constructor. They are created by Android.
Also in MyGestureListener the TextView is never initialised.
You should instead pass a reference to the TextView when you initialise a MyGestureListener object.
For example you can do something like this:
public class MainActivity extends AppCompatActivity {
TextView myText;
Button myButton;
private GestureDetectorCompat mDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText = (TextView)findViewById(R.id.myText);
myButton = (Button)findViewById(R.id.myButton);
mDetector = new GestureDetectorCompat(this, new MyGestureListener(myText));
myButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
myText.setText("I am clicked from button");
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private TextView myText;
public MyGestureListener(TextView textView) {
myText = textView;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
myText.setText("Scroll ho v ja hun");
return true;
}
}

You are never setting the myText MyGestureListener class. Try this:
myText = (TextView)findViewById(R.id.myText);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
mDetector.myText = myText;
For the code above to work myText will have to be public.
So change this:
private TextView myText;
to this:
public TextView myText;

Related

How can I perform onClickListener on two object using interface in Android Studio?

I have a Fragment class which extends View.onClickListener and I have implement #overriden method i.e onClick.
I have 2 imageView which performs onClickListener.
filterIcon.setOnClickListener(this)
fab.setOnClickListener(this)
And set both activities in #overriden method i.e. onClick().
I want to know can this is possible that onClickListener will call the related clickEvent? If yes, how? If not, why?
Here's my code :
public class ExpenseFragment extends Fragment implements View.OnClickListener {
private TextView totalExpenseTV;
private FloatingActionButton fab;
private RecyclerView recyclerView;
private ImageView filterIcon;
private PieChart pieChart;
private Animation rotateForward, rotateBackward;
private FirebaseRecyclerOptions<ExpenseModel> options;
private MyAdapter adapter;
private int calendarImgClick = 0;
private int groceryClick = 0;
private int bikeClick = 0;
private int rentClick = 0;
private int foodsClick = 0;
private int beerClick = 0;
private int setCalClick = 0;
private String whichCategorySelected = "";
private String selectedDate;
public void onViewCreated(#NonNull View attachInParentView, Bundle savedInstanceState) {
super.onViewCreated(attachInParentView, savedInstanceState);
findViewByIDS(attachInParentView);
setupRecyclerView();
fabAnimation();
fab.setOnClickListener(this);
filterIcon.setOnClickListener(this);
databaseListener();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_expense, container, false);
}
#Override
public void onClick(View view) {
fab.startAnimation(rotateForward);
rotateForward.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
addNote();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
filterIcon.setBackgroundResource(R.drawable.filter_off);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.filterIcon) {
// codul care se executează când este apăsată imaginea filterIcon
} else if (view.getId() == R.id.fab) {
// codul care se executează când este apăsată imaginea fab
}
}
You could try this using Kotlin:
#Override
public void onClick(View view) {
when (view.getId) {
R.id.filterIcon -> {
//do something
}
R.id.fab -> {
//do something
}
}
}

Like hitting counter in recyclerview

How to implement like button hitting count in RecyclerView. I have already created a like button and counter TextView with this code but when I hit the like button the application crashes. This is my code, what's wrong? I am using toggle button for like option and a TextView for counting like hitting.
This is my viewholder
public class WritingsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView MainTitle;
public ImageView Mainimage;
public ImageView Profimage;
public TextView ProfName;
public TextView txv;
public ToggleButton liketglbtn;
public TextView MainDesc, Idvkanme;
private ItemClickListner itemClickListner;
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
public WritingsViewHolder(View itemView) {
super(itemView);
MainTitle = (TextView)itemView.findViewById(R.id.RTitle);
Mainimage = (ImageView)itemView.findViewById(R.id.rImageView);
Profimage = (ImageView)itemView.findViewById(R.id.Profile_Image);
ProfName = (TextView)itemView.findViewById(R.id.Prof_Name);
MainDesc = (TextView)itemView.findViewById(R.id.rDescriptionTv);
Idvkanme = (TextView)itemView.findViewById(R.id.Idavaka_Name);
txv = (TextView)itemView.findViewById(R.id.tx);
liketglbtn = (ToggleButton) itemView.findViewById(R.id.likeToggleBtn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickListner.onClick(v,getAdapterPosition(),false);
}
}
This is my activity
public class WritingsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseRecyclerOptions<IdavakaModel> options;
FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder> adapter;
DatabaseReference MCC;
String categoryId = "";
RecyclerView.LayoutManager layoutManager;
TextView smsCountText;
int pendingSMSCount = 10;
static Button notifCount;
static int mNotifCount = 0;
Button FBcard, YoutubeCard;
private static final String APP_ID = "ca-app-pub-8867939169855032~9998384849";
Button mSaveBtn, mShareBtn;
private long backPressedTime;
private Toast backToast;
private int mCounter = 0;
ToggleButton btn;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writings);
FBcard = (Button) findViewById(R.id.button1);
FBcard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(WritingsActivity.this, IdavakaNewsUploadActivity.class);
startActivity(toy);
WritingsActivity.this.finish();
}
});
MobileAds.initialize(this,APP_ID);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Bottom Navigation Bar
final BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.botmnavigation);
bottomNavigationView.setSelectedItemId(R.id.action_privacy);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.myhome:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_notification:
startActivity(new Intent(getApplicationContext(),ChristianNewsMainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_privacy:
return true;
}
return false;
}
});
MCC= FirebaseDatabase.getInstance().getReference().child("Writings");
recyclerView = (RecyclerView) findViewById(R.id.readingroom_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
LoadData(categoryId);
}
private void LoadData(String categoryId) {
options = new FirebaseRecyclerOptions.Builder<IdavakaModel>().setQuery(MCC,IdavakaModel.class).build();
adapter = new FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull WritingsViewHolder writingsViewHolder, int i, #NonNull IdavakaModel idavakaModel) {
writingsViewHolder.MainTitle.setText(idavakaModel.getTitle());
writingsViewHolder.MainDesc.setText(idavakaModel.getDesc());
writingsViewHolder.ProfName.setText(idavakaModel.getProfname());
writingsViewHolder.Idvkanme.setText(idavakaModel.getIdavakaname());
Picasso.get().load(idavakaModel.getPostimage())
.into(writingsViewHolder.Mainimage);
Picasso.get().load(idavakaModel.getProfimage())
.into(writingsViewHolder.Profimage);
writingsViewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent detailsIntent = new Intent(WritingsActivity.this, IdavakaDetailActivity.class);
detailsIntent.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(detailsIntent);
}
});
writingsViewHolder.liketglbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#NonNull
#Override
public WritingsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.writngs_items, parent, false);
return new WritingsViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
super.onBackPressed();
WritingsActivity.this.finish();
return;
} else {
backToast = Toast.makeText(getBaseContext(), "See You Soon", Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
WritingsActivity.this.finish();
}
public void onCustomToggleClick (View view) {
Toast.makeText(this, "Liked",Toast.LENGTH_SHORT).show();
}
}
You are getting NullPointerException because the TextView you are using is in Activity named txv where you are setting counter. But the problem is you have declared TextView in Activity but have not initialized anywhere in the Activity. You MUST initialize that variable via findViewbyId method before setting values.
Furthermore, you have initialized txv TextView and accessing on Activity that is why you are getting NLP. TextView is a part of Activity layout which you have not Initialized. On the hand you have initialized txv in Adapter which is of no use.

app crashed when I launch another activity after a countdown of 3 sec

This is my MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main2);
CountDownTimer countDownTimer = new CountDownTimer (3000,1000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
startActivity (new Intent (MainActivity.this, Main2Activity.class));
}
}.start ();
} }
Here is my Main2Activity.java
public class Main2Activity extends AppCompatActivity {
public static Button button;
public static TextView temp;
public static TextView cityname;
public static TextView time;
public static EditText written;
public static ImageView imageView;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
button = (Button) findViewById (R.id.button);
temp = (TextView) findViewById (R.id.temp);
cityname = (TextView) findViewById (R.id.cityname);
time = (TextView) findViewById (R.id.time);
relativeLayout = (RelativeLayout) findViewById (R.id.relative);
written = (EditText) findViewById (R.id.editText);
imageView = (ImageView) findViewById (R.id.imageView);
button.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
try {
if(written.getText ().toString ().isEmpty () || written.getText ().toString ().equals ("")){
Toast.makeText (Main2Activity.this, "Enter your City name", Toast.LENGTH_LONG).show ();
}else {
time.setAlpha (0f);
temp.setAlpha (0f);
cityname.setAlpha (0f);
Parsing parsing = new Parsing ();
parsing.execute ();
written.setText("");
}
}catch (Exception e){
}
}
});
} }
This app crashed when I press the button, without anything the app crashes.

How can I send data from PageAdapter to an activity that extends Activity class

I have a problem in my android app. In my app after click on btn_back_story01, I need to send a boolean variable (that called newPermit) from a PageViewer (that called customeSwipeAdapter) to an activity that extends Activity class. The pageViewer is:
public class CustomSwipeAdapter01 extends PagerAdapter {
private int[] image_Resources = {R.drawable.sample_01, R.drawable.sample_02, R.drawable.sample_03, R.drawable.sample_04, R.drawable.sample_05, R.drawable.sample_06, R.drawable.sample_07};
private Context ctx;
private LayoutInflater layoutInflater;
boolean newPermit;
public CustomSwipeAdapter01(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_Resources.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return (view == (RelativeLayout) o);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view = layoutInflater.inflate(R.layout.activity_story01, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.image_view);
TextView textView = (TextView) item_view.findViewById(R.id.image_count);
Button btn_back_story01 = (Button) item_view.findViewById(R.id.btn_back_story01);
imageView.setImageResource(image_Resources[position]);
int itemNo = position + 1;
textView.setText(itemNo + "/" + getCount());
container.addView(item_view);
newPermit=false;
btn_back_story01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newPermit = true;
((Activity) ctx).finish();
ctx.startActivity(intent);
boolean over=false;
}
});
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout) object);
}}
and the activity is:
public class Story01 extends Activity {
ViewPager viewPager;
CustomSwipeAdapter01 adapter;
Button btn_back_story01;
boolean permit, oldPermit;
protected TestClass app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewer);
app = (TestClass) getApplication();
viewPager = (ViewPager) findViewById(R.id.view_pager);
btn_back_story01 = (Button) findViewById(R.id.btn_back_story01);
adapter = new CustomSwipeAdapter01(this);
viewPager.setAdapter(adapter);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
#Override
protected void onStart() {
permit = false;
super.onStart();
}
#Override
protected void onStop() {
if (permit == false) {
app.musicStop();
}
Intent intent = new Intent(getApplicationContext(), MainStory01.class);
startActivity(intent);
finish();
super.onStop();
}}
I know it is simple but when you don't know a simple thing it will be difficault.
You can use a listener. You create an interface which you can make callbacks with. Then you make you activity implement this and make sure its passed to your adapter to use.
CustomSwipeAdapter01
public class CustomSwipeAdapter01 extends PagerAdapter {
public interface NewPermitListener {
void onPermitClicked(boolean over);
}
private NewPermitListener mListener;
...
public CustomSwipeAdapter01(Context ctx, NewPermitListener listener) {
this.ctx = ctx;
// pass the listener in the constructor
mListener = listener;
}
...
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
...
btn_back_story01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// call the method
mListener.onPermitClicked(false);
}
});
return item_view;
}
}
Story01
public class Story01 extends Activity implements CustomSwipeAdapter01.NewPermitListener{
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewer);
...
// pass the listener in here
adapter = new CustomSwipeAdapter01(this, this);
viewPager.setAdapter(adapter);
}
#Override
public void onPermitClicked(boolean over) {
// do something with boolean
}
...
}

Example of how to change textView Color onTouch?

been working on a prject for a while, now I want it so that when the user touches the screen it changes the color of the textView(DigitalClock). I'm a bit of a noob when it comes to java so I really need a fully working example if possible? Here's my code so far:
public class MainActivity extends Activity {
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Handler handler = new RandomMoveHandler((TextView) findViewById(R.id.digitalClock1));
handler.sendEmptyMessage(0);
}
private static class RandomMoveHandler extends Handler {
private final WeakReference<TextView> textViewWeakReference;
private RandomMoveHandler(TextView textView) {
this.textViewWeakReference = new WeakReference<TextView>(textView);
}
#Override
public void handleMessage(Message msg) {
TextView textView = textViewWeakReference.get();
if (textView == null) {
Log.i(TAG, "WeakReference is gone so giving up.");
return;
}
int x = RANDOM.nextInt(670 - 100);
int y = RANDOM.nextInt(1230 - 100);
Log.i(TAG, String.format("Moving text view to (%d, %d)", x, y));
textView.setX(x);
textView.setY(y);
//change the text position here
this.sendEmptyMessageDelayed(0, 30000);
}
}
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// use any of your own colors here...
textView.setTextColor(android.R.color.holo_purple);
return true;
}
});
See also https://developer.android.com/reference/android/widget/TextView.html#setTextColor(int)

Categories