I have viewpager in which each fragment has videoview now I want to show buttons over that view pager. I am using frame layout for that. but still not able to make those buttons visible overview pager. only fragments in my view pager are visible but the buttons which I want to show over viewpager pager are not getting visible.
when activity starts at that time buttons are shown for 2.3 secs when as soon as video in fragment become visible that buttons are not visible
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:custom="http://schemas.android.com/apk/res-auto"
tools:context=".Activities.MenuButtonActivity">
<com.abp.app.ViewPager.NonSwipeableViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="#+id/rl_bottom_overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="yyyyyyyy"
android:visibility="visible" >
<Button
android:id="#+id/btn_left_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="35dp"
android:text="yyyyyyyy" />
<Button
android:id="#+id/btn_below_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="35dp"
android:text="yyyyyyyy"
android:visibility="visible" />
<Button
android:id="#+id/btn_right_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="50dp"
android:text="yyyyyyyy"
android:layout_toRightOf="#id/btn_left_arrow" />
</RelativeLayout>
</FrameLayout>
here is the code of acitivity
package com.abp.app.Activities;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.abp.app.Adapter.MyPageAdapter;
import com.abp.app.CallerFuntionClasses.FunctionsCallApiFromServer;
import com.abp.app.Fragments.ConnectivityFragment;
import com.abp.app.Fragments.LondonRoyalDocksFragment;
import com.abp.app.Fragments.MasterPlanFragment;
import com.abp.app.Fragments.OfficesFragment;
import com.abp.app.Fragments.ProjectTeamFragment;
import com.abp.app.Fragments.VideosFragment;
import com.abp.app.R;
import com.abp.app.Utilities.AppVeriableClass;
import com.abp.app.Utilities.CustomSharePreferences;
import com.abp.app.Utilities.UtilsForDownloadDataFromServer;
import com.abp.app.ViewPager.NonSwipeableViewPager;
import java.util.ArrayList;
import java.util.List;
import static android.widget.RelativeLayout.ABOVE;
public class MenuButtonActivity extends AppCompatActivity {
private Context context;
private Activity activity;
private int BtnHeight = 0;
private ProgressBar progressBar;
private TextView tv_progressCounting;
private static String dirPath;
boolean doubleBackToExit = false;
FrameLayout frameLayout;
RelativeLayout.LayoutParams params;
FunctionsCallApiFromServer apiFromServer;
String accessTokenType,accessToken;
SharedPreferences sharedPreferences;
CustomSharePreferences customSharePreferences = new CustomSharePreferences();
ConnectivityManager conMgr;
NetworkInfo netInfo;
ArrayList<String> test;
///////////// Fragments //////////
MasterPlanFragment masterPlanFragment ;
OfficesFragment officesFragment;
ConnectivityFragment connectivityFragment ;
VideosFragment videosFragment ;
LondonRoyalDocksFragment londonRoyalDocksFragment;
ProjectTeamFragment projectTeamFragment ;
MyPageAdapter pageAdapter;
com.abp.app.ViewPager.NonSwipeableViewPager viewpager;
////////////////////////////////////
private android.support.v4.app.FragmentTransaction fragmentTransaction;
final Handler handler = new Handler();
private static final int[] menuBtnIdsArray = {R.id.btn_masterplan,R.id.btn_Offices,R.id.btn_connectivity,R.id.btn_londonroyaldock,R.id.btn_videos,R.id.btn_projectteam};
private ArrayList<Button> menuBtnArrayList = new ArrayList<Button>();
private int previousClickedButton = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manu_buttons);
viewpager = (com.abp.app.ViewPager.NonSwipeableViewPager)findViewById(R.id.viewpager);
viewpager.setPagingEnabled(false);
List fragments = getFragmetns();
pageAdapter = new MyPageAdapter( getSupportFragmentManager(),getFragmetns());
viewpager.setAdapter(pageAdapter);
VariableInitialize();
// CallAPIFromServer();
hideStatusBar();
// onclickBtnFrangment();
// firstTimeAlwaysCallFragment();
}
private void firstTimeAlwaysCallFragment() {
frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
setFragment(masterPlanFragment);
menuBtnArrayList.get(0).setBackgroundColor(menuBtnArrayList.get(0).getContext().getResources().getColor(R.color.button_pressed));
}
private void VariableInitialize(){
context = MenuButtonActivity.this;
activity = MenuButtonActivity.this;
////////////// Fragment Initialize/////////////////
masterPlanFragment = new MasterPlanFragment();
officesFragment = new OfficesFragment();
connectivityFragment = new ConnectivityFragment();
londonRoyalDocksFragment = new LondonRoyalDocksFragment();
videosFragment = new VideosFragment();
projectTeamFragment = new ProjectTeamFragment();
////////////////////////////////
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo= conMgr.getActiveNetworkInfo();
apiFromServer = new FunctionsCallApiFromServer();
sharedPreferences = context.getSharedPreferences("AccessToken",Context.MODE_PRIVATE);
accessToken = sharedPreferences.getString("Token",null);
accessTokenType = sharedPreferences.getString("Type",null);
dirPath = UtilsForDownloadDataFromServer.getRootDirPath(getApplicationContext());
// frameLayout = (FrameLayout)findViewById(R.id.mainContainter_fragment);
params = new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
//tv_progressCounting = (TextView)findViewById(R.id.textViewProgressCount);
//progressBar = (ProgressBar)findViewById(R.id.progressbar);
}
private void onclickBtnFrangment(){
for (int i = 0; i< menuBtnIdsArray.length; i++){
final int currentBtnSelected = i;
menuBtnArrayList.add((Button)findViewById( menuBtnIdsArray[i]));
try {
menuBtnArrayList.get(currentBtnSelected).setText(AppVeriableClass.getInstance().menuDisplayNames.get(i));
} catch (Exception e) {
e.printStackTrace();
}
menuBtnArrayList.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (menuBtnArrayList.get(currentBtnSelected).getId()) {
case R.id.btn_masterplan:
setFragment(masterPlanFragment);
frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
selectedBtnColorChange(currentBtnSelected);
break;
case R.id.btn_Offices:
setFragment(officesFragment);
frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
selectedBtnColorChange(currentBtnSelected);
break;
case R.id.btn_connectivity:
setFragment(connectivityFragment);
frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));// display full screen
selectedBtnColorChange(currentBtnSelected);
break;
case R.id.btn_londonroyaldock:
setFragment(londonRoyalDocksFragment);
// params.addRule(ABOVE,R.id.linearlayout); // display show above on the menu bar as per the requirement.
frameLayout.setLayoutParams(params);
selectedBtnColorChange(currentBtnSelected);
break;
case R.id.btn_videos:
setFragment(videosFragment);
// params.addRule(ABOVE,R.id.linearlayout); // display show above on the menu bar as per the requirement.
frameLayout.setLayoutParams(params);
selectedBtnColorChange(currentBtnSelected);
break;
case R.id.btn_projectteam:
setFragment(projectTeamFragment);
frameLayout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT));
selectedBtnColorChange(currentBtnSelected);
break;
}
}
});
}
}
// After click the menu button this function change the color of button until you press the other button.
private void selectedBtnColorChange(int current) {
menuBtnArrayList.get(previousClickedButton).setBackgroundColor(menuBtnArrayList.get(previousClickedButton).getContext().getResources().getColor(R.color.button_default));
menuBtnArrayList.get(previousClickedButton).setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
menuBtnArrayList.get(current).setBackgroundColor(menuBtnArrayList.get(current).getContext().getResources().getColor(R.color.button_pressed));
if (BtnHeight == menuBtnArrayList.get(current).getHeight()){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, BtnHeight);
menuBtnArrayList.get(current).setLayoutParams(params);
}
else{
BtnHeight = menuBtnArrayList.get(current).getHeight() + 10;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, BtnHeight);
menuBtnArrayList.get(current).setLayoutParams(params);
}
previousClickedButton = current;
}
private void hideStatusBar(){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public void onBackPressed(){
if (doubleBackToExit){
super.onBackPressed();
return;
}
else
Toast.makeText(context, "Click again to exit", Toast.LENGTH_SHORT).show();
this.doubleBackToExit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit = false;
}
},2000);
}
private void CallAPIFromServer(){
if (netInfo != null) {
apiFromServer.getMediaResourceOffices(context, activity, accessTokenType, accessToken);
apiFromServer.getMediaResourceConnectivity(context, accessTokenType, accessToken);
apiFromServer.getMediaResourceLondonRoyalDock(context, accessTokenType, accessToken);
apiFromServer.getMediaResouceVideo(context, accessTokenType, accessToken);
}
}
public void onResume() {
super.onResume();
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo= conMgr.getActiveNetworkInfo();
}
private void setFragment(Fragment fragment){
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainContainter_fragment,fragment);
fragmentTransaction.commit();
}
private List<Fragment> getFragmetns()
{
List<Fragment> flist = new ArrayList<>();
flist.add(MasterPlanFragment.NewIntance());
flist.add(OfficesFragment.NewIntance());
flist.add(ConnectivityFragment.NewIntance());
flist.add(VideosFragment.NewIntance());
flist.add(ProjectTeamFragment.NewIntance());
return flist;
}
}
Try this solution.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.MenuButtonActivity">
<com.abp.app.ViewPager.NonSwipeableViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="#+id/rl_bottom_overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="horizontal"
android:text="yyyyyyyy"
android:visibility="visible">
<Button
android:id="#+id/btn_left_arrow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="yyyyyyyy"/>
<Button
android:id="#+id/btn_below_share"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="yyyyyyyy"
android:visibility="visible"/>
<Button
android:id="#+id/btn_right_arrow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="yyyyyyyy"/>
</LinearLayout>
</FrameLayout>
And the result is.
Related
This is the code I have been working on for a while. The only issue is I cannot seem to be able to get the sum of values input into the editText fields that are dynamically added into the program and then place them into a pie chart. The data is to be transferred from the second activity to the third where the third activity will add up all resource amounts and display them into a pie chart.
SecondActivity.class
package com.example.a4mob;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.drawerlayout.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayout linearLayout;
private Button add;
//for button add resource
List<String> ColourList = new ArrayList<>();
ArrayList<Results> resultList = new ArrayList<>();
private Button submit;
private Number uinput;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.secondactivity);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
// Define ColorDrawable object and parse color
// using parseColor method
// with color hash code as its parameter
ColorDrawable colorDrawable
= new ColorDrawable(Color.parseColor("grey"));
// Set BackgroundDrawable
actionBar.setBackgroundDrawable(colorDrawable);
//Adds more objects
linearLayout = findViewById(R.id.layout_list);
add = findViewById(R.id.CreateNew);
add.setOnClickListener(this);
ColourList.add("grey");
ColourList.add("green");
ColourList.add("blue");
ColourList.add("yellow");
// Creating submit button click listener
submit = findViewById(R.id.Submit);
submit.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId()){
case R.id.CreateNew:
addView();
break;
case R.id.Submit:
if(isValid()){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", resultList);
intent.putExtras(bundle);
startActivity(intent);
}
break;
}
}
private boolean isValid() {
resultList.clear();
boolean valid = true;
for(int i = 0; i < linearLayout.getChildCount(); i++){
View resultView = linearLayout.getChildAt(i);
EditText resultName = (EditText) resultView.findViewById(R.id.RName);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) resultView.findViewById(R.id.ColourOP);
Results results = new Results();
if(!resultName.getText().toString().equals("")){
results.setResName(resultName.getText().toString());
}else{
valid = false;
break;
}
if(!resultNumber.getText().toString().equals("")){
results.setResAmount(Integer.parseInt(resultNumber.getText().toString()));
}else{
valid = false;
break;
}
if(COP.getSelectedItemPosition()!=0){
}else{
valid = false;
break;
}
resultList.add(results);
}
if(resultList.size() == 0){
valid = false;
Toast.makeText(this, "Complete all fields first", Toast.LENGTH_SHORT).show();
} else if(!valid){
Toast.makeText(this, "Enter details correctly", Toast.LENGTH_SHORT).show();
}
return valid;
}
public void addAmount(){
for(int i = 0; i < linearLayout.getChildCount(); i++) {
View resultView = linearLayout.getChildAt(i);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
Results results = new Results();
}
}
private void sub(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please input inventory space:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
uinput = input.getInputType();
changeAct();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void changeAct(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
private void addView(){
View newResource = getLayoutInflater().inflate(R.layout.row_add_data, null, false);
ImageView imageClose = (ImageView)newResource.findViewById(R.id.Remove);
TextView RN = (TextView) newResource.findViewById(R.id.RName);
TextView RA = (TextView) newResource.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) newResource.findViewById(R.id.ColourOP);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ColourList);
COP.setAdapter(arrayAdapter);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(newResource);
}
});
linearLayout.addView(newResource);
}
private void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
}
ThirdActivity.class
package com.example.a4mob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ThirdActivity extends AppCompatActivity {
RecyclerView recycle_results;
ArrayList<Results> resultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
recycle_results = findViewById(R.id.res_results);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recycle_results.setLayoutManager(linearLayoutManager);
resultList = (ArrayList<Results>) getIntent().getExtras().getSerializable("list");
recycle_results.setAdapter(new ResultsAdapter(resultList));
}
}
Results.class
package com.example.a4mob;
import java.io.Serializable;
public class Results implements Serializable {
public String resourceName;
public int resourceAmount;
public int totalAmount;
public Results(){
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getResAmount() {
return resourceAmount;
}
public void setResAmount(int resourceAmount) {
this.resourceAmount = resourceAmount;
}
public Results(String resourceName, int resourceAmount){
this.resourceName = resourceName;
this.resourceAmount = resourceAmount;
}
public String getResName() {
return resourceName;
}
public void setResName(String resourceName) {
this.resourceName = resourceName;
}
}
ResultsAdapter.class
package com.example.a4mob;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.ResultsView> {
ArrayList<Results> resultList = new ArrayList<>();
int total;
public ResultsAdapter(ArrayList<Results> resultList) {
this.resultList = resultList;
}
#NonNull
#Override
public ResultsView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_results,parent,false);
return new ResultsView(view);
}
#Override
public void onBindViewHolder(#NonNull ResultsView holder, int position) {
Results results = resultList.get(position);
holder.resourceName.setText(results.getResName());
holder.resourceAmount.setText(String.valueOf(results.getResAmount()));
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ResultsView extends RecyclerView.ViewHolder{
TextView resourceName, resourceAmount, resourceTotal;
public ResultsView(#NonNull View itemView) {
super(itemView);
resourceName = (TextView) itemView.findViewById(R.id.resNa);
resourceAmount = (TextView) itemView.findViewById(R.id.resAm);
resourceTotal = (TextView) itemView.findViewById(R.id.resTot);
}
}
}
thirdactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ThirdActivity">
<LinearLayout
android:id="#+id/layoutThird"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/res_results"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
row_results.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
android:layout_marginBottom="20dp"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/resNa"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Name"
android:textSize="18sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resAm"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resTot"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>
Profile.java
package com.synergywebdesigners.veebee;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Profile extends AppCompatActivity {
public TextView user,pass,email,mob,add;
public Button ChangePass;
FragmentManager fragmentManager = Profile.this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final FrameLayout frame = (FrameLayout) findViewById(R.id.chg_frag);
user = (TextView) findViewById(R.id.user);
pass = (TextView) findViewById(R.id.pass);
email = (TextView) findViewById(R.id.email);
mob = (TextView) findViewById(R.id.mob);
add = (TextView) findViewById(R.id.add);
ChangePass = (Button) findViewById(R.id.chang_pass);
ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction = fragmentManager.beginTransaction();
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll);
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
String url = Config.DATA_URL+user;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Profile.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String users="";
String passw="";
String emails = "";
String mobile = "";
String address = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
users = collegeData.getString(Config.KEY_UNAME);
passw = collegeData.getString(Config.KEY_PASS);
emails = collegeData.getString(Config.KEY_EMAIL);
mobile = collegeData.getString(Config.KEY_MOB);
address = collegeData.getString(Config.KEY_ADD);
} catch (JSONException e) {
e.printStackTrace();
}
user.setText("User :\t"+users);
pass.setText("Password :\t"+passw);
email.setText("Email Id :\t"+emails);
mob.setText("Mob No :\t"+mobile);
add.setText("Address :\t"+address);
}
//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(Config.USERNAME_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(Profile.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Adding our menu to toolbar
getMenuInflater().inflate(R.menu.vee_bee, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
//calling logout method when the logout button is clicked
logout();
}
return super.onOptionsItemSelected(item);
}
}
activity_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scroll"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:background="#drawable/side_nav_bar"
tools:context="com.synergywebdesigners.veebee.Profile">
<RelativeLayout
android:id="#+id/profile_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/margin_header"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/margin_header"
android:background="#drawable/side_nav_bar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:id="#+id/linearLayout1"
android:gravity="center">
<TextView
android:id="#+id/user_profile_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/name"
android:textAllCaps="true"
android:textColor="#color/defaults"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/user_profile_short_bio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/user_profile_name"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:text="#string/web_add"
android:textColor="#color/defaults"
android:textSize="14sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColor="#color/defaults"
android:textStyle="bold"
android:clickable="true"
android:textAllCaps="true"
android:id="#+id/m_org"
android:gravity="center"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#id/user_profile_short_bio"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="vertical"
android:id="#+id/linearLayout"
android:layout_below="#+id/linearLayout1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/user" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/pass"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/email"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/mob"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/add"/>
</LinearLayout>
<Button
android:id="#+id/chang_pass"
android:layout_below="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin_header"
android:background="#color/colorPrimaryDark"
android:textColor="#color/defaults"
android:textAllCaps="true"
android:textStyle="bold"
android:text="Change Password"/>
<FrameLayout
android:layout_below="#id/chang_pass"
android:id="#+id/chg_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
</ScrollView>
ChangePass.java
package com.synergywebdesigners.veebee;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
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;
import android.widget.Toast;
import java.util.HashMap;
public class ChangPass extends Fragment {
public EditText PrevPass,NewPass;
public Button Conform;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_chang_pass,container,false);
PrevPass = (EditText) view.findViewById(R.id.prev_pass);
NewPass = (EditText) view.findViewById(R.id.new_pass);
Conform = (Button) view.findViewById(R.id.send);
Conform.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChangePass();
//getActivity().finish();
}
});
return view;
}
private void ChangePass(){
class Addmessage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
String prevpass = PrevPass.getText().toString().trim();
String newpass = NewPass.getText().toString().trim();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(),"Sending Request..","..Please..Wait..",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getActivity(),s,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_PASS_USER,user);
params.put(Config.KEY_PREV_PASS,prevpass);
params.put(Config.KEY_NEW_PASS,newpass);
ReuestHandler rh = new ReuestHandler();
String res = rh.sendPostRequest(Config.URL_CHANG_PASS, params);
return res;
}
}
Addmessage ae = new Addmessage();
ae.execute();
}
}
fragment_chang_pass.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.synergywebdesigners.veebee.ChangPass">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/lbl_prev"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/defaults"
android:textStyle="bold"
android:text="Your Current Password"/>
<EditText
android:id="#+id/prev_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_below="#+id/lbl_prev"
android:singleLine="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Password"
android:textColor="#color/defaults"
android:id="#+id/lbl_new"
android:textStyle="bold"
android:layout_below="#+id/prev_pass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/new_pass"
android:inputType="text"
android:singleLine="true"
android:layout_below="#+id/lbl_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/send"
android:padding="10dp"
android:layout_below="#+id/new_pass"
android:textColor="#color/defaults"
android:background="#color/colorPrimary"
android:text="Confirm Password Change"
/>
</RelativeLayout>
</FrameLayout>
In the code, I want to add Conform button click listener event call Android back button. Like click on back button in fragment close fragment in this time.
public void pushFragment(Fragment fragment, boolean shouldAdd, Bundle bundle) {
stackFragmentMain.push(fragment);
FragmentManager man = getSupportFragmentManager();
FragmentTransaction ft = man.beginTransaction();
ft.replace(R.id.main_screens, fragmentholder.fragment);
ft.commitAllowingStateLoss();
}
public void popFragment() {
if (stackFragmentMain.size() >= 1) {
Fragment fragment = stackFragmentMain
.elementAt(stackFragmentMain.size() - 2);
stackFragmentMain.pop();
if (fragmentholder != null) {
FragmentManager man = getSupportFragmentManager();
FragmentTransaction ft = man.beginTransaction();
ft.replace(R.id.main_screens, fragmentholder.fragment);
ft.commitAllowingStateLoss();
}
}
}
EDIT
Change the following part of your onClick method :-
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction = fragmentManager.beginTransaction();
to
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
EDIT 2
Along with the above change, in your Conform.onClickListener() of your ChangePass fragment, add the following code :-
getActivity().getSupportFragmentManager().popBackStack();
I've difficult with changing activity on android.
I started my app(display main.xml) and clicked Start button(display listening.xml).
When I had pressed back button, background disappeared on my app.
[display main.xml]
[display listening.xml]
detecting display.. (A image not attached because I have less reputation :( )
[display main.xml (Problem)]
Following is my source code.
(Some code are omitted.)
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
LayoutInflater inflater = LayoutInflater.from(this);
mainView = inflater.inflate(R.layout.main, null);
listeningView = inflater.inflate(R.layout.listening, null);
setContentView(mainView);
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start Button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe Button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
setContentView(listeningView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "종료");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) { // Start Button
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02) // ReadMe Button
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
// omitted..
}
Please give me some advice.
Sorry for my bad english.
Thanks in advance.
Following are added context.
I tried to change inflater to setContentView().
But, It's not worked.
I clicked start button and touched back key on my phone.
My phone said "Unfortunately, (MY_APP_NAME) has stopped."
I reupload my source code.
[MainActivity.java]
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
// LayoutInflater inflater = LayoutInflater.from(this); // disable inflater
setContentView(R.layout.main);
// mainView = inflater.inflate(R.layout.main, null); // disable inflater
// listeningView = inflater.inflate(R.layout.listening, null); // disable inflater
// setContentView(mainView); // disable inflater
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
//setContentView(listeningView);
setContentView(R.layout.listening);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Exit");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
NotificationManager notiMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notiMgr.cancel(999); // Notification의 고유 id가 999인 것을 찾아서 notification을 종료한다.
finish();
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) {
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02)
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
private void Threadsleep(DetectorThread detectorThread){
try
{
detectorThread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onWhistleDetected() {
runOnUiThread(new Runnable() {
public void run() {
TextView textView = (TextView)
MainActivity.mainApp.findViewById(R.id.detectedNumberText);
textView.setText(String.valueOf(numWhistleDetected++));
if (numWhistleDetected > 1) {
setEvent();
}
}
});
Threadsleep(detectorThread);
}
}
[main.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/car">
<Button
android:id="#+id/whistleButton"
android:layout_width="150dp"
android:layout_height="40dp"
android:gravity="center"
android:text="Start"
android:textSize="20dp"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
<Button
android:id="#+id/whistleButton02"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_below="#id/whistleButton"
android:gravity="center"
android:text="ReadMe"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:textSize="20dp"
android:layout_marginTop="15dp"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
</RelativeLayout>
[listening.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background ="#drawable/worker"
>
<TextView
android:id="#+id/listening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:textSize="30dp"
android:text="Detecting.." />
<TextView
android:id="#+id/detectedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:layout_centerInParent="true"
android:textSize="20dp" />
<TextView
android:id="#+id/detectedNumberText"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:textSize="5dp"
android:layout_toRightOf="#+id/detectedText"
/>
</RelativeLayout>
[help.xml]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="112dp"
android:layout_marginTop="20dp"
android:text="Read Me...." />
</RelativeLayout>
[AndroidManifest.xml]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.musicg.demo.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="#drawable/ear"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".listening"></activity>
<activity android:name="help"></activity>
</application>
</manifest>
First of all Use setContentView(R.layout.main) in onCreate() in your oncreate as Akhil mentioned instead of inflating.
Also to set background image to your activity use android:background="#drawable/image_name" to your root container in main.xml.
If you are trying to dynamically switch the image in your lisenter.
Try and let us know if it worked.
Also to get more understanding can to show contents of your main.xml ?
I have an Android application with a very simple main activity. It only has two buttons, one textview and one edittext field. I launch the main activity (I don't do anything, just launch it from app drawer), then I press home button to get to my home screen, go to settings > appmanager > running > cached background processes and there I see that my app is eating more RAM than other cached background processes, around 8 MB of RAM. Is it normal? Why is it eating more than other apps? This is my code:
MainActivity:
package com.example.myapp;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
long maxMemory = Runtime.getRuntime().maxMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
Log.i("ilog", "memoryClass: " + memoryClass);
Log.i("ilog", "maxMemory: " + maxMemory);
Log.i("ilog", "totalMemory: " + totalMemory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private Button button1;
private Button button2;
private TextView textView1;
private EditText editText1;
private ComponentName cn;
private String disable = "Disable app";
private String enable = "Enable app";
private int enabledState;
private PackageManager pm;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
button1 = (Button) rootView.findViewById(R.id.button1);
editText1 = (EditText) rootView.findViewById(R.id.editText1);
textView1 = (TextView) rootView.findViewById(R.id.textView1);
button2 = (Button) rootView.findViewById(R.id.button2);
cn = new ComponentName(getActivity(), CallReceiver.class);
pm = getActivity().getPackageManager();
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
button1.setText(disable);
} else {
button1.setText(enable);
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
button1.setText(enable);
} else {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
button1.setText(disable);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText1.getText().toString().length() > 0) {
Intent callImitateIntent = new Intent(getActivity(), CallReceiver.class);
callImitateIntent.putExtra(TelephonyManager.EXTRA_STATE, TelephonyManager.EXTRA_STATE_RINGING);
callImitateIntent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, editText1.getText().toString());
getActivity().sendBroadcast(callImitateIntent);
} else textView1.setText("Invalid incoming number");
}
});
return rootView;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Intent serviceStopIntent = new Intent(this, WindowService.class);
stopService(serviceStopIntent);
}
}
fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myapp.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/welcome" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:maxLength="12"
android:hint="#string/edittext1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/button2" />
</RelativeLayout>
So can anyone tell me why is it eating so much RAM? Thanks in advance!