onBackPressed() finishes my Activity - java

In my project I have just one Activity that have View.
I think that it has two View that switch the View. The first View is my home that has one Button named "play" . when You click play Button in goes to the second View. Second View is my game.
And now my problem is that when I want to use onBackPressed() method in the second View, it closes the Activity. and onBackPressed() method do the same in both View.
How to handle onBackPressed() method in second View that return to the first View.
How to switch the View in onBackPressed()?
I am new with Android and now I really confused.
any suggestion? or any key word to search to solve my problem.
here is my code:
public class PTPlayer extends Cocos2dxActivity {
static Splash splash;
public static AppList appList;
static Noti_Queue noti_queue;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("----------", "onActivityResult: request: " + requestCode + " result: " + resultCode);
if (requestCode == PTServicesBridge.RC_SIGN_IN) {
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (appList == null) {
appList = new AppList(this);
appList.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
}
#Override
public void onNativeInit() {
initBridges();
}
private void initBridges() {
PTStoreBridge.initBridge(this);
PTServicesBridge.initBridge(this, getString(R.string.app_id));
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kRevMob")) {
PTAdRevMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAdMob") || PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdAdMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAppLovin")) {
PTAdAppLovinBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kLeadBolt")) {
PTAdLeadBoltBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kVungle")) {
PTAdVungleBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kPlayhaven")) {
PTAdUpsightBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kMoPub")) {
PTAdMoPubBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdFacebookBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kHeyzap")) {
PTAdHeyzapBridge.initBridge(this);
}
}
#Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 0, 0, 0);
return glSurfaceView;
}
static {
System.loadLibrary("player");
}
#Override
protected void onResume() {
super.onResume();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onResume(this);
}
}
#Override
protected void onStart() {
super.onStart();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStart(this);
}
}
#Override
protected void onStop() {
super.onStop();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStop(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
}
here i think that in my second view:
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private Cocos2dxGLSurfaceView mGLSurfaceView;
private Cocos2dxHandler mHandler;
private static Context sContext = null;
public static Context getContext() {
return sContext;
}
// ===========================================================
// Constructors
// ===========================================================
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sContext = this;
this.mHandler = new Cocos2dxHandler(this);
this.init();
Cocos2dxHelper.init(this, this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
}
#Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
}
#Override
public void showDialog(final String pTitle, final String pMessage) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
this.mHandler.sendMessage(msg);
}
#Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
this.mHandler.sendMessage(msg);
}
#Override
public void runOnGLThread(final Runnable pRunnable) {
this.mGLSurfaceView.queueEvent(pRunnable);
}
// ===========================================================
// Methods
// ===========================================================
public void init() {
// FrameLayout
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
FrameLayout framelayout = new FrameLayout(this);
framelayout.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout
ViewGroup.LayoutParams edittext_layout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
this.mGLSurfaceView = this.onCreateView();
// Switch to supported OpenGL (ARGB888) mode on emulator
if (isAndroidEmulator())
this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
RelativeLayout relativeLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
relativeLayout.setLayoutParams(params);
//AdView adad = new AdView(this);
ClickBanner_CLickYab_Holder adad = new ClickBanner_CLickYab_Holder(this);
RelativeLayout.LayoutParams adad_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
adad_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// adad.setToken(getString(R.string.adad_token));
adad.setLayoutParams(adad_params);
Button myButton = new Button(this);
myButton.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton.setLayoutParams(adad_params1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
Button myButton1 = new Button(this);
myButton1.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton1.setLayoutParams(adad_params2);
myButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
relativeLayout.addView(this.mGLSurfaceView);
relativeLayout.addView(adad);
relativeLayout.addView(myButton);
relativeLayout.addView(myButton1);
ClickBanner_CLickYab_Holder.setTestMode();
setContentView(relativeLayout);
}
public Cocos2dxGLSurfaceView onCreateView() {
return new Cocos2dxGLSurfaceView(this);
}
private final static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
}

you must use of Override Method for when back button pressed
if you want to stay on currnt activity use like this
#Override
public void onBackPressed() {
return;
}
if you want to use double click to exit and one click to stay you can use like this
first define a variable for double click
boolean doubleBackToExit = false;
and the Override backbutton method
#Override
public void onBackPressed() {
if (doubleBackToExit) {
//on double back button pressed
return;
}
this.doubleBackToExit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit=false;
}
}, 2000);
}

Then do this.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(MainActivityPhase2.this, GlobalSearch.class);
startActivity(intent);
finish();
}

Just don't call the super.onBackPressed() everytime.
#Override
public void onBackPressed() {
if (isFirstView()) {
super.onBackPressed();
} else {
switchToFirstView();
}
Call in only when there isn't any last view available. Or where you want to close the App. The code will finish your activity when you are on the first activity. And switch to first activity if you are on second activity.
Just replace my methods as per your code.

Overriding onBackPressed() of the activity and provide your screen where you want to go.
onBackpressed() check which is the current view you are showing and according to move to the first view.

in your second class Cocos2dxActivity, place this code.
#Override
public void onBackPressed() {
this.finish();
}

If you have just one activity with two View you can use Fragments.
Using Fragments, Activity.OnBackPressed() will remove last fragment in the stack and you can resolve your problem.
So, in the activity you have to put a container in xml layout file:
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:clickable="true" android:layout_height="match_parent"/>
In the Activity java file:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourHomeFragment())
.commit();
So to add second Fragment you can use this code:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
Pay attention: you can call this code or in YourHomeFragment class (into button clickListener) or in your Activity (using a callback system). For example:
In YourHomeFragment -->
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
}
});
In this way, you have to declare two layout xml file for fragments and one for Activity.
List of java and relative xml files:
MainActivity.java
activity_main.xml
YourHomeFragment.java
fragment_your_home.xml <-- insert here your first View
YourPlayFragment.java
fragment_your_play.xml <-- play view

Related

How To Add Multiple Cards Of The Same CardView To A RecyclerView?

Here is a video of what I trying to do and explanation of the issue that I am having. Go to the following link below.
https://file.re/2021/09/12/2021-09-1210-43-21/
Here is the XML, Java, and Manifest Code Video. Go to the following link below.
https://file.re/2021/09/12/2021-09-1211-32-13/
Answer worked, but now I have two new problems. Here is the video link below.
https://file.re/2021/09/12/2021-09-1212-08-04/
I am creating an app that lists CardView layouts to a RecyclerView.
My app will add the CardView layout to the RecyclerView list, but it only lists one. I want it to add multiples of the same CardView when the user clicks on the button to add the card (basically cloning the CardView layout one under the other).
Here is what I have in my Button Click...
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
addFahToCelCard.add(new RecyclerItem());
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
}
}
});
I've tried putting the ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); under the MainActivity extends AppCompatActivity class just before the onCreate like this...
public class MainActivity extends AppCompatActivity {
final private ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
That didn't work.
If I don't keep ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); in the button click listener, and I add a new CardView it will add a new one behind the original one each time the button is clicked, and if I delete the card it keep popping back up until I delete them all off. How do I fix this the way I want it to behave? I hope this all makes sense.
I appreciate the help!
Here is everything in the java class..
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addFahToCelCard;
private Animation fromBottom;
private Animation toBottom;
private Boolean clicked = false;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public FloatingActionButton mainConverterMenuFloatBtn;
public TextView chooseConverterLabel, ftocConverterLabelBtn, ftokConverterLabelBtn, ctofConverterLabelBtn, ctokConverterLabelBtn, ktofConverterLabelBtn, ktocConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.from_bottom_animation);
toBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.to_bottom_animation);
mainConverterMenuFloatBtn = findViewById(R.id.add_temp_converter_float_btn);
chooseConverterLabel = findViewById(R.id.choose_converter_label);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ctofConverterLabelBtn = findViewById(R.id.add_c_to_f_converter_label_btn);
ctokConverterLabelBtn = findViewById(R.id.add_c_to_k_converter_label_btn);
ktofConverterLabelBtn = findViewById(R.id.add_k_to_f_converter_label_btn);
ktocConverterLabelBtn = findViewById(R.id.add_k_to_c_converter_label_btn);
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
mainConverterMenuFloatBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainConverterMenu();
}
});
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
}
private void addFahToCelCard() {
}
private void mainConverterMenu() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setVisibility(View.VISIBLE);
ftocConverterLabelBtn.setVisibility(View.VISIBLE);
ftokConverterLabelBtn.setVisibility(View.VISIBLE);
ctofConverterLabelBtn.setVisibility(View.VISIBLE);
ctokConverterLabelBtn.setVisibility(View.VISIBLE);
ktofConverterLabelBtn.setVisibility(View.VISIBLE);
ktocConverterLabelBtn.setVisibility(View.VISIBLE);
} else {
chooseConverterLabel.setVisibility(View.GONE);
ftocConverterLabelBtn.setVisibility(View.GONE);
ftokConverterLabelBtn.setVisibility(View.GONE);
ctofConverterLabelBtn.setVisibility(View.GONE);
ctokConverterLabelBtn.setVisibility(View.GONE);
ktofConverterLabelBtn.setVisibility(View.GONE);
ktocConverterLabelBtn.setVisibility(View.GONE);
}
}
private void setClickable(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setClickable(true);
ftocConverterLabelBtn.setClickable(true);
ftokConverterLabelBtn.setClickable(true);
ctofConverterLabelBtn.setClickable(true);
ctokConverterLabelBtn.setClickable(true);
ktofConverterLabelBtn.setClickable(true);
ktocConverterLabelBtn.setClickable(true);
} else {
chooseConverterLabel.setClickable(false);
ftocConverterLabelBtn.setClickable(false);
ftokConverterLabelBtn.setClickable(false);
ctofConverterLabelBtn.setClickable(false);
ctokConverterLabelBtn.setClickable(false);
ktofConverterLabelBtn.setClickable(false);
ktocConverterLabelBtn.setClickable(false);
}
}
private void setAnimation(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.startAnimation(fromBottom);
ftocConverterLabelBtn.startAnimation(fromBottom);
ftokConverterLabelBtn.startAnimation(fromBottom);
ctofConverterLabelBtn.startAnimation(fromBottom);
ctokConverterLabelBtn.startAnimation(fromBottom);
ktofConverterLabelBtn.startAnimation(fromBottom);
ktocConverterLabelBtn.startAnimation(fromBottom);
} else {
chooseConverterLabel.startAnimation(toBottom);
ftocConverterLabelBtn.startAnimation(toBottom);
ftokConverterLabelBtn.startAnimation(toBottom);
ctofConverterLabelBtn.startAnimation(toBottom);
ctokConverterLabelBtn.startAnimation(toBottom);
ktofConverterLabelBtn.startAnimation(toBottom);
ktocConverterLabelBtn.startAnimation(toBottom);
}
}
private void closeActionButton() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.show_hide_float_convert_btn) {
if (mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.GONE);
item.setIcon(R.drawable.ic_baseline_visibility_off_32);
} else if (!mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.VISIBLE);
item.setIcon(R.drawable.ic_baseline_visibility_32);
}
} else if (id == R.id.app_help) {
} else if (id == R.id.tip_developer) {
} else if (id == R.id.premium_features) {
} else if (id == R.id.about_app) {
} else if (id == R.id.exit_app) {
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView fahtoCelResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
fahtoCelResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
holder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = holder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if(!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
holder.fahtoCelResult.setText(nf.format(dddd) + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = nf.format(dddd) + "°C";
holder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
}else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
holder.fahtoCelResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}});
adb.create();
adb.show();
return false;
}
});
holder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
}
The recyclerView should be listing the CardViews and also allowing duplicates.
Well, I think you are just using the RecyclerView the wrong way.
In your code snippet, you are initializing the RecyclerView as well as the adapter and all other components every time the user clicks the button.
First of all you will have to create the insert method in the RecyclerItemAdapter class.
RecyclerItemAdapter.java
class RecyclerItemAdapter extends RecyclerView.Adapter<YourViewHolder> {
private ArrayList<RecyclerItem> items;
RecyclerItemAdapter(ArrayList<RecyclerItem> recyclerItems) {
this.items = recyclerItems;
}
//...
public void addItem(RecyclerItem item) {
items.add(item);
notifyDataSetChanged();
}
}
Then, you have ton initialize the RecyclerView only once. The best place to do that is in the onCreate method.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<RecyclerItem> addFahToCelCard;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFahToCelCard = new ArrayList<>();
setupRecyclerView();
setupClickListener();
}
private void setupRecyclerView() {
recyclerView = findViewById(R.id.recycler_item_view);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerItemAdapter);
}
}
Now add your onClickListener which will only add the card to the list.
private void setupClickListener() {
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemAdapter.addItem(new RecyclerItem());
}
});
}
What is your xml layout for this cardview ? It looks like this cardview is in another layout that has match parent as width and height.
If thats the case items are too big to show.
Okay so try making first reletive layout height = 100dp to match the card view in fahrenheit_to_celsius_converter_layout.xml
well I didn't understand the problem very well but from what I understood here's what you should do :
first you shouldn't be creating a new recycler view on every button click, instead you should put the code that initializes the recycler view in onCreate method that exist in the activity class and just keep a reference to the arraylist that holds the data and the adapter as global variables.
whenever the user clicks the button you should add a new item to the arraylist of data and use adapter.notifyDataItemSetChanged to tell the recycle view to check if there's any change happened to the recycle view and take action if necessary
here's a part of code that explains what I'm saying and I hope you that even if that doesn't answer your question, you catch a glimpse of how to deal with recyclerview :
first as I said you should keep a reference to the arraylist that holds the data and the adapter as global variables so put those outside any method in the activity
RecyclerItemAdapter recyclerItemAdapter ;
ArrayList <RecyclerItem>addFahToCelCard ;
and then put this code instead of the button code
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
}
}
});
that way whenever you want to edit the recyclerView data anytime you can add/remove items from the global arraylist and notify the adapter just like the code inside the button OnClickListener
update to the last video posted about the exception
this problem raises when you delete some items, try to use holder.getAbsoluteAdapterPosition(), instead of getAdapterPosition or the old final position value.
whenever you use a value inside a listener I guess it takes the value that exists right now and hold it as final, so if you have 5 items and deleted the first 3, the last two will still have their position stored as 4 and 5 instead of 1 and 2, thats why you should call the holder.getAbsoluteAdapterPosition() to get the current position instead of the final stored one, that way he stores the holder as final instead of storing a const int value.

When I click on next song my seekbar sometimes gets updated and sometimes not. I am not getting what's the error in my code probably with the seekbar

**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}

How can I do AsyncLayoutInflater onCreate

The content part of the android application consisted of a lot of code structure. (3000 lines) I divided them into 3 viewstubs. I started 3 handler nested and then inflated the viewstubs.
But it did not accelerate again. it still opens very slowly. Now, while researching, I encountered asyntasklayoutinflater, but I think I couldn't do this job properly. No view appears in the content. // I deleted setContentView I also want to move my viewstubs into asynctask, but it is not static, how can I do this? Could you help?
Thanks in advance!
ViewStub viewStub1;
ViewStub viewStub2;
ViewStub viewStub3;
View coachStub1;
View coachStub2;
View coachStub3;
#SuppressLint("InflateParams")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
new AsyncLayoutInflater(this).inflate(R.layout.activity_main, null, new AsyncLayoutInflater.OnInflateFinishedListener() {
#Override
public void onInflateFinished(#NonNull View view, int resid, #Nullable ViewGroup parent) {
long start = System.currentTimeMillis();
viewStub1 = view.findViewById(R.id.viewStub1);
viewStub2 = view.findViewById(R.id.viewStub2);
viewStub3 = view.findViewById(R.id.viewStub3);
viewStub1.setLayoutResource(R.layout.viewstub1);
coachStub1 = viewStub1.inflate();
viewStub2.setLayoutResource(R.layout.viewstub2);
coachStub2 = viewStub2.inflate();
viewStub3.setLayoutResource(R.layout.viewstub3);
coachStub3 = viewStub3.inflate();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Objects.requireNonNull(notificationManager).cancelAll();
initialize(view);
new MainAsyncTask(MainActivity.this).execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
VKIPagerAdapter = new MyViewPagerAdapter();
vkipager.setAdapter(VKIPagerAdapter);
VKIPagerAdapter.notifyDataSetChanged();
vkipager.setOffscreenPageLimit(10);
vkipager.addOnPageChangeListener(viewPagerPageChangeListener);
long finish = System.currentTimeMillis();
Log.d("Handler Displayed", "\t" + (finish - start));
}
}, 100);
menu1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
///
}
});
inters_ad1 = new InterstitialAd(context);
inters_ad2 = new InterstitialAd(context);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (blink_settings && !MainActivity.this.isFinishing()) {
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500);
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
profile.startAnimation(anim);
}
}
}, 8000);
}
});
}
AsyncTask
private static class MainAsyncTask extends AsyncTask<Integer, Integer, String> {
private WeakReference<MainActivity> activityWeakReference;
MainAsyncTask(MainActivity activity) {
activityWeakReference = new WeakReference<>(activity);
}
#Override
protected String doInBackground(Integer... integers) {
MainActivity activity = activityWeakReference.get();
activity.sharedPreferencesKeys();
activity.alertDialogClickListener();
activity.changeListener();
return "MainAsyncTask Worked!";
}
#Override
protected void onPostExecute(String s) {
Log.d("MainAsyncTask", "" + s);
}
}
init method
private void initialize(View view) {
loadframe = view.findViewById(R.id.loadframe);
menu = view.findViewById(R.id.menu);
bottombar = view.findViewById(R.id.bottombar);
menu1 = view.findViewById(R.id.menu1);
pageIndicator = coachStub1.findViewById(R.id.pageIndicator);
vkisonuctw = coachStub1.findViewById(R.id.vkisonuctw);
numberpicker = coachStub2.findViewById(R.id.numberpicker);
radiogrouphareket = coachStub2.findViewById(R.id.radiogrouphareket);
belkalcasonuctw = coachStub3.findViewById(R.id.belkalcasonuctw);
belkalcasonuctwinfo = coachStub3.findViewById(R.id.belkalcasonuctwinfo);
// much more
}
You have to load the view asynchronously,Call this method setcontentview (view) to set it to activity
like this:
new AsyncLayoutInflater(context).inflate(layout, null, new AsyncLayoutInflater.OnInflateFinishedListener() {
#Override
public void onInflateFinished(#NonNull View view, int resid, #Nullable ViewGroup parent) {
//load view into activity
activity.setContentView(view);
}
});

how to use data from child activity in MainActivity and use it as parameter in other methods

I want to send data from EditText in child activity to parent activity (MainActivity) and use it as a string parameter (URL) in other methods
Already I am able to send this using intent and extras, also I added textview in method to see if it works, but finally, this textview will be deleted, but I can't use it in other methods
public class MainActivity extends AppCompatActivity implements OnDataSendToActivity {
ImageView bg_state;
Button btn_rl;
TextView txt_network;
String url;
String my_url;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bg_state = findViewById(R.id.bg_status);
txt_network = findViewById(R.id.txt_network);
Toolbar toolbar= findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=findViewById(R.id.tV);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isNetworkAvailable()){
bg_state.setImageResource(R.drawable.background);
txt_network.setText("");
}else{
bg_state.setImageResource(R.drawable.background_on);
txt_network.setText("Cound not connect to the server");
}
updateStatus();
handler.postDelayed(this, 2000);
}
}, 5000); //the time is in miliseconds
btn_rl = findViewById(R.id.sw_1);
btn_rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url_rl = my_url+"room_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});
String url_rl = url+"bed_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.conf){
Intent intent_conf = new Intent(MainActivity.this, Configuration.class);
startActivityForResult(intent_conf,1);
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1){
if(resultCode==RESULT_OK){
url=data.getStringExtra("url");
my_url="http://"+url;
tv.setText(my_url);
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void sendData(String str) {
updateButtonStatus(str);
}
private void updateStatus(){
String url_rl = my_url+"status";
StatusTask task = new StatusTask(url_rl, this);
task.execute();
}
//Function for updating Button Status
private void updateButtonStatus(String jsonStrings){
try {
JSONObject json = new JSONObject(jsonStrings);
String room_light = json.getString("rl");
if(room_light.equals("1")){
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90off);
}else{
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90on);
}
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.power_off);
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
childactivity
public class Configuration extends AppCompatActivity {
public String new_url;
EditText ip_text;
Button sub_btn;
String a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
Toolbar tool = findViewById(R.id.toolbar);
setSupportActionBar(tool);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
findViewById(R.id.wifi_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl("https://192.168.4.1");
}
});
ip_text = findViewById(R.id.ip_text);
sub_btn= findViewById(R.id.sub_btn);
sub_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Configuration.this,MainActivity.class);
new_url=ip_text.getText().toString();
i.putExtra("url",new_url);
setResult(RESULT_OK,i);
finish();
}
});
}
}
What I need is that if I write in Configuration class for example 192.168.xx.xx In mainactivity my_url will be my_url="https://192.168/ and it will be able to use in other methods as a parameter (for example in btn_rl.setOnClickListener).

Autocomplete search bar using Google Places API in a fragment

My app currently looks like this:
I want to add a search bar where I can search any place as Google maps. The search bar should be in an Auto Complete way.I got this code from https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/
Have a look at the above link.
And these codes where for an ORDINARY APP to get Auto Complete search bar. It doesnt suit for app using fragment. And I dont know how to do it with fragments.
Here is my code
For the Main Activity (ProfileActivity)
public class ProfileActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_user, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i == R.id.ButtonBarFeed)
{
NewsFragment f = new NewsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarMap)
{
MapFragment f = new MapFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarUser)
{
UserFragment f = new UserFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0,"#28809f");
}
public boolean googleServicesAvailable(){
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(api.isUserResolvableError(isAvailable)){
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this,"Can't connet to Play Services", Toast.LENGTH_LONG).show();
}
return false;
}
boolean twice;
#Override
public void onBackPressed() {
Log.d(TAG, "click");
if(twice == true){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice:" + twice);
Toast.makeText(ProfileActivity.this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice:" + twice);
}
}, 3000);
}
}
MapFragment
public class MapFragment extends Fragment implements OnMapReadyCallback {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapView1);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap){
}
}
I have to add a search bar with Auto Complete like Google map.Please with reference of the Link which I have given at starting, Can Anyone code for my MapFragment?

Categories