I am having some trouble. I followed every guide online showing how to override a parent method in a child class. I have done everything I was told to do, yet my child function does nothing.
My MainActivity(Parent) class:
package com.example.flashcards;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DatabseHelper DB = new DatabseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeText();
changeText2();
};
public void changeText(){}
public void changeText2(){}
String [] columns = new String[] {
DatabseHelper.FLASHCARD_QUESTION,
DatabseHelper.FLASHCARD_ANSWER
};
#Override
public void onClick(View v) {
}
}
My child class (TextC)
package com.example.flashcards;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TextC extends MainActivity {
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
My changeText() function does nothing. I am not getting any errors, so I can not tell what I am doing wrong. Do I need to create an onCreate method for the child class? But I am extending MainActivity which has it.
Any ideas on why my method overriding is not working?
With inheritance and overriding concepts, you need to override onCreate function in your child class. And from that overridden method, you can make a call to super.onCreate or you can do this.chnageText and this.changeText2 from child class.
Otherwise when you call onCreate function, it will call changeText and changeText2 from super class only.
In your child class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.changeText();
this.changeText2();
};
Modify parent class
package com.example.flashcards;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DatabseHelper DB = new DatabseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//changeText(); freeze or remove these callings
//changeText2();
};
public void changeText(){}
public void changeText2(){}
}
And add some code to your child class
package com.example.flashcards;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TextC extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
changeText();
changeText2();
};
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
In the above method there is no point declare changeText(); and changeText2(); in parent activity. For the sake of reusability, we can use abstract classes and methods.
Do some changes to your parent activity as you see below.
public abstract class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeText(); // they dont have default implimentation in parent so it will be invoked from child class where these methods implimented
changeText2();
};
public abstract void changeText(); //there is no default implimentation
public abstract void changeText2();
}
And in child activity, you have to implement those methods.
public class TextC extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//changeText(); no need to call these methods bcz its already called in parent onCreate()
//changeText2();
};
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
Related
Now I'm studying Threads and my task is to make a counter, which will add number from 0 to 9 to TextView with the help of Loader. Of course, I know that it isn't the best variant to use Loader for such tasks, but I'd like to understand how does it work.
So, I have the following code:
package asus.example.com.exercise4;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class LoaderActivity extends AppCompatActivity {
private TextView counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_threads);
Button startButton = findViewById(R.id.start_button);
Button cancelButton = findViewById(R.id.cancel_button);
startButton.setOnClickListener(listener);
cancelButton.setOnClickListener(listener);
counter = findViewById(R.id.counter);
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start_button:
getSupportLoaderManager().initLoader(0, null, new LoaderClass());
break;
case R.id.cancel_button:
break;
}
}
};
#SuppressLint("StaticFieldLeak")
class AsyncTaskLoaderClass extends AsyncTaskLoader<Void>{
AsyncTaskLoaderClass(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public Void loadInBackground() {
for (int i = 0; i<10;i++){
counter.setText(i);
SystemClock.sleep(500);
}
return null;
}
}
private class LoaderClass implements LoaderManager.LoaderCallbacks<Void>{
#NonNull
#Override
public Loader<Void> onCreateLoader(int i, #Nullable Bundle bundle) {
return new LoaderActivity.AsyncTaskLoaderClass(LoaderActivity.this);
}
#SuppressLint("SetTextI18n")
#Override
public void onLoadFinished(#NonNull Loader<Void> loader, Void aVoid) {
counter.setText("Done!");
}
#Override
public void onLoaderReset(#NonNull Loader<Void> loader) {
}
}
}
When I run the project I have a runtime error:
java.lang.IllegalArgumentException: Object returned from onCreateLoader must not be a non-static inner member class: AsyncTaskLoaderClass{eed39bf id=0}
Yes, I understand, that it means that AsyncTaskLoaderClass should be in another file or static, but in such case I won't have an opportunity to add text to textview. So, how can I solve this problem?
UPD
I changed the code in clicking start button in such way:
case R.id.start_button:
Loader loader = getSupportLoaderManager().initLoader(0, null, LoaderActivity.this);
loader.forceLoad();
Log.i(TAG, "Button start clicked");
break;
And now each time in the loop I have the following error:
E/e.com.exercise: Invalid ID 0x00000009.
E/EventBus: Could not dispatch event: class asus.example.com.exercise4.LoaderActivity$MyAsyncTaskLoader$ProgressEvent to subscribing class class asus.example.com.exercise4.LoaderActivity
android.content.res.Resources$NotFoundException: String resource ID #0x9
UPD 2
Finally fixed the problem in the following way:
Was
counter.setText(i);
Now
counter.setText(""+i);
Probably I don't understrand why it works, but it works
Make the Activity implement LoaderCallbacks. Also a Loader retrieves one particular value in its onLoadFinished callback, and it should return the retrieved (loaded) item as a result.
To change what value is being loaded by a Loader, you're supposed to restart the loader with a new argument bundle, and pass in the parameters so that it knows what it is doing.
Then again, you are trying to create something like "publishProgress" in AsyncTask; Loaders cannot do that out of the box, and need some variant of "sending an event" (handler threads if you are adventurous, but most likely an event bus, see implementation 'org.greenrobot:eventbus:3.1.1').
TL;DR: use EventBus for this.
public class LoaderActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Void> {
private TextView counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_threads);
Button startButton = findViewById(R.id.start_button);
Button cancelButton = findViewById(R.id.cancel_button);
counter = findViewById(R.id.counter);
startButton.setOnClickListener((view) -> {
getSupportLoaderManager().initLoader(0, null, LoaderActivity.this);
});
cancelButton.setOnClickListener((view) -> {
// do nothing, apparently
});
EventBus.getDefault().register(this);
}
#Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onLoaderProgressEvent(MyAsyncTaskLoader.ProgressEvent event) {
counter.setText("" + event.getNumber());
}
#NonNull
#Override
public Loader<Void> onCreateLoader(int i, #Nullable Bundle bundle) {
return new MyAsyncTaskLoader(LoaderActivity.this);
}
#SuppressLint("SetTextI18n")
#Override
public void onLoadFinished(#NonNull Loader<Void> loader, Void aVoid) {
counter.setText("Done!");
}
#Override
public void onLoaderReset(#NonNull Loader<Void> loader) {
}
public static class MyAsyncTaskLoader extends AsyncTaskLoader<Void> {
public static class ProgressEvent {
private final int number;
public ProgressEvent(int number) {
this.number = number;
}
public int getNumber() { return number; }
}
public MyAsyncTaskLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public Void loadInBackground() {
for (int i = 0; i<10;i++){
EventBus.getDefault().post(new ProgressEvent(i));
SystemClock.sleep(500);
}
return null;
}
}
}
Your are using inner AsyncTaskLoaderClass in Activity class. Inner class holds the reference of Outer class. That means your AsyncTaskLoaderClass may hold Activity reference in some cases. Make your inner class static.
You have 2 solutions. Make AsyncTaskLoaderClass a separate class file or make AsyncTaskLoaderClass a static class.
make textview public static like this public static TextView counter;
first of all pardon my English, but I think it's understandable.
So in this app is a counter and I need it to do sound when it reaches for example 30 seconds.
note: this is my first question here so if I broke any rules or I could have asked better way, let me know please
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends AppCompatActivity {
private Button mStartButton;
private Button mPauseButton;
private Button mResetButton;
private Chronometer mChronometer;
private long lastPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartButton = (Button) findViewById(R.id.start_button);
mPauseButton = (Button) findViewById(R.id.pause_button);
mResetButton = (Button) findViewById(R.id.reset_button);
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (lastPause != 0){
mChronometer.setBase(mChronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
}
else{
mChronometer.setBase(SystemClock.elapsedRealtime());
}
mChronometer.start();
mStartButton.setEnabled(false);
mPauseButton.setEnabled(true);
}
});
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
mChronometer.stop();
mPauseButton.setEnabled(false);
mStartButton.setEnabled(true);
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChronometer.stop();
mChronometer.setBase(SystemClock.elapsedRealtime());
lastPause = 0;
mStartButton.setEnabled(true);
mPauseButton.setEnabled(false);
}
});
}
}
Define global integer variable as counter and count it in Chronometer's OnChronometerTickListener, and when it reach for example 30 then play sound and reset your counter:
int c = -1; // define global
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
c++;
if(c == 30) {
c = 0;
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.ding);
mp.start();
}
}
});
what i'm trying to do:
in FirstFragment the user can type in his weight.
in SecondFragment the weight should be shown in a TextView
the Value should be passed on swipe of the user.
i tried arround 3 how-to's and read a lot about fragments but i still couldn't find a suitable solution. As i'm kind of new to fragments it could also be that i made a uncommon way to generate fragments and it therefore doesn't work but i couldn't figure it out yet.
As you can se unerneath actually there is an error in the code because i tried to get access to the method of FirstFragment through the MainActivity
To simplyfy, i don't poste the whole code of the two fragment xlm's.
first_frag.xml have a EditText (id: getWeight) Box where you only can enter numbers up to 3 digits
second_frag.xml has a TextView (id: txtAlcLvl)
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
MainActivity.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
Calculator calc = new Calculator();
ViewPager pager;
private MyPagerAdapter myPagerAdapter;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
public Calculator getCalc(){
return this.calc;
}
public void getWeight(){
FragmentManager fm = getSupportFragmentManager();
FirstFragment fragment = (FirstFragment)fm.findFragmentById(R.id.i_dont_know_the_id);
//failure because trying to get access to Method of FirstFragment
fragment.getWeight();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int i, final float v, final int i2) {
}
#Override
public void onPageSelected(final int i) {
YourFragmentInterface fragment = (YourFragmentInterface) pagerAdapter.instantiateItem(pager, i);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(final int i) {
}
});
}
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 1: return new SecondFragment(); //SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return new FirstFragment();
default: return new FirstFragment(); //FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
FirstFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FirstFragment extends Fragment implements MainActivity.YourFragmentInterface {
Button btnBeer;
Button btnBeerSmall;
Button btnWine;
Button btnLiq;
Button btnSch;
Button btnWater;
Button btnMale;
Button btnFemale;
Calculator calc;
EditText getWeight;
public String getWeight(){
return getWeight.getText().toString();
}
#Override
public void fragmentBecameVisible() {
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
btnBeer = (Button) v.findViewById(R.id.btnBeer);
btnBeerSmall = (Button) v.findViewById(R.id.btnBeerSmall);
btnWine = (Button) v.findViewById(R.id.btnWine);
btnLiq = (Button) v.findViewById(R.id.btnLiq);
btnSch = (Button) v.findViewById(R.id.btnSch);
btnWater = (Button) v.findViewById((R.id.btnWater));
btnMale = (Button) v.findViewById(R.id.btnMale);
btnFemale = (Button) v.findViewById(R.id.btnFemale);
getWeight = (EditText) v.findViewById(R.id.getWeight);
btnBeer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(0);
}
});
btnBeerSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(1);
}
});
btnWine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(2);
}
});
btnLiq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(3);
}
});
btnSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(4);
}
});
btnWater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(5);
}
});
btnMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnMale.setBackgroundResource(R.drawable.male_false);
btnFemale.setBackgroundResource(R.drawable.female);
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnFemale.setBackgroundResource(R.drawable.female_false);
btnMale.setBackgroundResource(R.drawable.male);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class SecondFragment extends Fragment implements MainActivity.YourFragmentInterface {
TextView txtAlcLvl;
TextView txtTimeToZero;
TextView txtPeak;
ImageButton btnReset;
Calculator calc;
String weight;
#Override
public void fragmentBecameVisible() {
calc.person.setSex(false);
calc.person.setWeight(80);
txtAlcLvl.setText(((MainActivity) getActivity()).getWeight());
//txtAlcLvl.setText(String.format("%.2f", calc.getCurrentLevel()) + "‰");
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
public void setSex(){
}
public void setWeight(){
try{
} catch(NumberFormatException e){
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
txtAlcLvl = (TextView) v.findViewById(R.id.txtAlcLvl);
txtTimeToZero = (TextView) v.findViewById(R.id.txtTimeToZero);
txtPeak = (TextView) v.findViewById(R.id.txtPeak);
btnReset = (ImageButton) v.findViewById((R.id.btnReset));
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.resetConsumption();
}
});
return v;
}
public void updateText(String t){
txtAlcLvl.setText(t);
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You could do it the over way round.
Instead of trying to get the weight in activity from your fragment, try to set the weight on the activity from the fragment.
public class MainActivity extends FragmentActivity {
...
private float weight;
public void setWeight(float weight) {
this.weight = weight;
}
public float getWeight() {
return this.weight();
}
Then in your FirstFragment:
((MainActivity)getActivity()).setWeight(...);
And finally in your SecondFragment:
float weight = ((MainActivity)getActivity()).getWeight();
Don't try to "pass" the value like you would normally expect when an activity is invoking a new fragment.
Instead, consider using some persistent storage to store the value, such as SharedPreferences or a Sqlite database. Each fragment can read and write values out of there as needed.
I create a application using DialogFragment.I want to get the Data from DialogFragment and setText in the MainActivity. In my Code I successfully Created the AlertDialog.But I con't able to get the EditText value to MainActivity.Application is crashed.Please help me to solve the problem.Any Help would be I really Appreciate.
MainActivity.java :
public class MainActivity extends ActionBarActivity {
Button showDialog;
TextView showText;
String myNameStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.myBtn);
showText = (TextView)findViewById(R.id.showText);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
showText.setText(myNameStr);
}
}
MyAlert.java:
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
MainActivity mainActivity = new MainActivity();
mainActivity.setMyNameStr(value);
dialog.dismiss();
}
}
Using this Procedure Application is Crashed.
replace from
MainActivity mainActivity = new MainActivity();
to:
Activity mainActivity = (MainActivity)getActivity();
Create an interface like-
CustomDialogInterface.java
public interface CustomDialogInterface {
// This is just a regular method so it can return something or
// take arguments if you like.
public void okButtonClicked(String value);
}
and modify your MyAlert.java by-
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
CustomDialogInterface customDI;
public MyAlert(CustomDialogInterface customDI)
{
this.customDI = customDI;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
dialog.dismiss();
customDI.okButtonClicked(value);
}
void setCustomDialogInterface(CustomDialogInterface customDialogInterface){
this. customDI = customDialogInterface;
c}
}
And implement CustomDialogInterface in your MainActivity and overide method okButtonClicked()
When onClick will be called then your MainActivity's onButtonClicked will be called .
and change showAlert to -
class MainActivity..... implements CustomDialogInterface {
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.show(getFragmentManager(), "My New Alert");
}
#Overide
public void okButtonClicked(String value){
// handle
}
}
or use following code :
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.setCustomDialogInterface(new CustomDialogInterface() {
#Override
public void okButtonClicked(String value) {
//handle click
}
});
myAlert.show(getFragmentManager(), "My New Alert");
}
you can achieve this using a interface,by sending your data from a fragment to main activity,below i have edited your complete code and its working fine....
Here is the code with example
Your Main Activity
package com.example.dialogfragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity implements SetName{
Button showDialog;
TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.button1);
showText = (TextView)findViewById(R.id.textView2);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
}
#Override
public void setMyName(String string) {
// TODO Auto-generated method stub
showText.setText(string);
}
}
Your Alert
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
SetName setname;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
setname = (SetName) a;
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
// MainActivity mainActivity = new MainActivity();
setname .setMyName(value);
//setname = (SetName)
// setname = (SetName)getActivity();
dialog.dismiss();
}
}
Create a Interface
public interface SetName {
void setMyName(String string);
}
Now what you should do is create onAttach in your alertFragment and call your interface..
public void renameFile(){
RenameFileDialog dialog = new RenameFileDialog();
dialog.show(getSupportFragmentManager(), DIALOG_RENAME_FILE);
}
public void syncFolders(String value) {
//some code
new UpdateFolderAsyncTask().execute();
}
update listview with new updated value after performining operation in main activity class syncFolders() in DialogFragment class
CustomDialogFragment extends DialogFragment{
//some logic for performining operation
String updatedValue=edittext.getText();
MainActivity activity=(MainActivity)getActivity();
activity.syncFolders(updatedValue);
}
I'm trying to learn Java through a tutorial on Aide and have entered what I believed was the correct code:
package com.aide.trainer.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set main.xml as user interface layout
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.mainTextView1);
Button button = (Button) findViewById(R.id.mainButton1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View p1)
{
// TODO: Implement this method
TextView textView = (TextView) findViewById(R.id.mainTextView1);
textView.setText("Clicked");
}
});
button.setOnLongClickListener(new OnLongClickListener()
{
#Override
public void onLongClick(View p1)
{
}
});
}
}
But at public void onLongClick(View p1), there is an error around void that says:
The type of this method is incompatible with the type of the overridden method 'android.view.View.OnLongClickListener.onLongClick(android.view.View)'
I can't figure out what I did wrong. Does anyone know?
In an OnLongClickListener, onLongClick(…) must return boolean, not void.