AVLoadingIndicatorView Library not visible in app - android

added the library for showing loading effects but it is not visible or any effect is not seen. Although no error occurs but there is no effect seen when the network call begins. The show method doesnot have any effect. Currently im using using android version 4.1.2.
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="50dp">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/signin_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_gravity="center"
android:background="#drawable/ic_arrow_back_black_24dp"></ImageView>
</FrameLayout>
<TextView
android:id="#+id/txt_signIn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:background="#color/colorPrimary"
android:gravity="center"
android:padding="12dp"
android:text="#string/sign_in"
android:textColor="#color/white"
android:textSize="18dp"></TextView>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Sign in to TruePay"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"></TextView>
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="50dp">
<EditText
android:id="#+id/signin_email_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:hint="Username"
android:inputType="textEmailAddress"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_password"
android:layout_width="match_parent"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/signin_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:hint="#string/signin_password"
android:inputType="textPassword"></EditText>
</android.support.design.widget.TextInputLayout>
<TextView
android:id="#+id/forgot_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:clickable="true"
android:gravity="center"
android:padding="10dp"
android:text="#string/forgot_password"
android:textColor="#color/black"
android:textSize="18dp"
android:textStyle="bold"></TextView>
<TextView
android:id="#+id/use_device_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:gravity="center"
android:padding="10dp"
android:text="#string/device_code"
android:textColor="#color/black"
android:textSize="18dp"
android:textStyle="bold"></TextView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<com.wang.avi.AVLoadingIndicatorView
android:id="#+id/avi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
app:indicatorName="BallPulseIndicator" />
</RelativeLayout>
</LinearLayout>
java code
public class SignIn extends BaseSupportFragment {
private View view;
private ImageView backPage;
private TextView signInBtn;
private TextView forgotPassword;
private TextView deviiceCodes;
TextInputLayout emailLayout,passwordLayout;
EditText email,password;
private static SessionManagement sessionManagement;
AVLoadingIndicatorView avi;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.sign_in_fragment, container, false);
initiateUI();
setListener();
return view;
}
public void getTokenFromServer()
{
WeakHashMap<String, String> param = new WeakHashMap<>();
param.put("username",email.getText().toString());
param.put("password",password.getText().toString());
Log.e("param...", String.valueOf(param));
RetrofitInterface apiService = RetrofitClient.getClient().create(RetrofitInterface.class);
Observable<TokenModel> call = apiService.postFishDetails(param)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
call.subscribe(new Observer<TokenModel>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
//handle error
Log.e("access",e.toString());
try {
if (e instanceof HttpException) {
if (((HttpException) e).code() == 401) {
// GlobalBus.getBus().post(new TokenExpirationNotification("Token Expired"));
}
}
if (e instanceof IOException) {
}
} catch (Exception e1) {
}
}
#Override
public void onNext(TokenModel response)
{
Constant.ACCESS_TOKEN = "Bearer" + response.getAccessToken();
avi.hide();
Intent intent = new Intent(getActivity(), DrawerAct.class);
getActivity().startActivity(intent);
getActivity().finish();
}
});
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private void setListener() {
backPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
}
});
signInBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(TextUtils.isEmpty(email.getText().toString()))
{
emailLayout.setError("Enter Username");
requestFocus(email);
}
else if(TextUtils.isEmpty(password.getText().toString()))
{
passwordLayout.setError("Enter Password");
requestFocus(password);
}
else
{
avi.show();
getTokenFromServer();
}
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replaceFragment(R.id.frame_layout, new ForgotPassword());
}
});
deviiceCodes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replaceFragment(R.id.frame_layout, new DeviceCode());
}
});
}
private void initiateUI()
{
backPage = (ImageView) view.findViewById(R.id.signin_back_button);
signInBtn = (TextView) view.findViewById(R.id.txt_signIn);
forgotPassword = (TextView) view.findViewById(R.id.forgot_password);
deviiceCodes = (TextView) view.findViewById(R.id.use_device_code);
emailLayout=(TextInputLayout)view.findViewById(R.id.input_layout_email);
passwordLayout=(TextInputLayout)view.findViewById(R.id.input_layout_password);
email=(EditText)view.findViewById(R.id.signin_email_address);
password=(EditText)view.findViewById(R.id.signin_password);
avi=(AVLoadingIndicatorView)view.findViewById(R.id.avi);
}
}

Resolved the issue. Forgot to mention the indiacator color which is white by default so the loader was actually working but wasnt visible;
XML code
<com.wang.avi.AVLoadingIndicatorView
android:id="#+id/avi"
style="#style/AVLoadingIndicatorView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
app:indicatorColor="#color/colorPrimaryDark"
app:indicatorName="LineSpinFadeLoaderIndicator" />

Your parent layout is LinearLayout, try wrapping your main layout with a RelativeLayout and put the AVLoadingIndicatorView outside the LinearLayout

Just add
app:indicatorColor="#color/grovery_blue" - set your color here
that's all. Enjoy your coding...

Related

How to fetch data related to a clicked item in a recyclerView from room database to a new activity?

My app has a RawMaterialFragment that displays raw materials data in a recyclerView from room database.
I am trying to build a detail activity(MetrialItemView) to show up the details of an individual raw material by clicking or selecting the raw material from the recyclerView.
my problem is how to send the data from the adapter and how to receive the data in the MetrialItemView Activity and display it.
MaterialListAdapter:
public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {
private final LayoutInflater mInflater;
private FragmentRawMaterials mContext;
private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
RawMaterialsEntity mCurrent;
public MaterialListAdapter(FragmentRawMaterials context) {
mInflater = LayoutInflater.from(context.getActivity());
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView materialName;
private final TextView materialBrand;
private final TextView materialQuantity;
LinearLayout parentLayout;
private ViewHolder(View itemView) {
super(itemView);
materialName = itemView.findViewById(R.id.raw_material_name);
materialBrand = itemView.findViewById(R.id.raw_material_brand);
materialQuantity = itemView.findViewById(R.id.raw_material_quantity);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (mMaterial != null) {
mCurrent = mMaterial.get(position);
holder.materialName.setText(mCurrent.getRawMaterialName());
holder.materialBrand.setText(mCurrent.getRawMaterialBrand());
holder.materialQuantity.setText(String.valueOf(mCurrent.getRawMaterialQuantity()));
} else {
// Covers the case of data not being ready yet.
holder.materialName.setText("Name NA");
holder.materialBrand.setText("Brand NA");
holder.materialQuantity.setText("Quantity NA");
}
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
mContext.startActivity(intent);
}
});
}
public void setMaterial(List<RawMaterialsEntity> materials){
mMaterial = materials;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
#Override
public int getItemCount() {
if (mMaterial != null)
return mMaterial.size();
else return 0;
}
}
MaterialItemView:
public class MaterialItemView extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_item_view);
}
}
material_list_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Name:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Brand:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_brand_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Weight:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2000"
style="#style/OtherTextViewsBody"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="gm"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost per gm/ml:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.1"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Available Quantity:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Name:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Email:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah#panadh.com"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Phone:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+966555699517"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
</LinearLayout>
FragmentRawMaterials:
public class FragmentRawMaterials extends Fragment{
private RawMaterialViewModel mMaterialViewModel;
private static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_raw_materials, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
//FloatingActionButton fab to insert recipes
TextView emptyViewText = view.findViewById(R.id.empty_raw__materials_view);
FloatingActionButton fab = view.findViewById(R.id.fab_raw_materials);
fab.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), RawMaterialsEditor.class);
startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
});
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
//Decoration to add a line divider between recyclerView items
DividerItemDecoration decoration =
new DividerItemDecoration(Objects.requireNonNull(this.getActivity()),
R.drawable.border_line);
recyclerView.addItemDecoration(decoration);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
final MaterialListAdapter adapter = new MaterialListAdapter(this);
recyclerView.setAdapter(adapter);
// Check if adapter list is empty, if so empty text view will appear.
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyViewText.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emptyViewText.setVisibility(View.GONE);
}
}
});
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
// Update the cached copy of the words in the adapter.
mMaterialViewModel.getAllMaterials().observe(this, adapter::setMaterial);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
RawMaterialsEntity material = new RawMaterialsEntity(data
.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
mMaterialViewModel.insertMaterial(material);
mMaterialViewModel.costPerGm();
mMaterialViewModel.totalCost();
} else {
Toast.makeText(
Objects.requireNonNull(getActivity()).getApplicationContext(),
R.string.editor_insert_rm_failed,
Toast.LENGTH_LONG).show();
}
}
}
each row of dataModel() must have ID and then use putExtra() whan clicked It happens
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
intent.putExtra("ID",mCurrent.getID());
mContext.startActivity(intent);
}
});
and use getIntent() in detailActivity
int id =getIntent().getIntExtra("ID",-1);
and then get a row data in detail activity from database(viewModel)by ID and parse it

Display corresponding details of user when selected from list

I have developed a screen where a no. of people from the database are displayed in a list view. I want to display the profile page of the selected person. So my question is how to bind each detail of the selected person like name, contact, etc. to the profile page which I have created? Will I have to call the getById API in the onItemClickListener?
Here's the edited code:-
public class Test extends AppCompatActivity {
List<Genie> genieList;
GenieAdapter genieAdapter;
TextView responseView;
ProgressBar progressBar;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
responseView = (TextView) findViewById(R.id.responseView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
button = (Button) findViewById(R.id.test);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Test.this, "Blahblah", Toast.LENGTH_LONG).show();
new RetrieveFeedTask().execute();
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, List<Genie>> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected List<Genie> doInBackground(Void... urls) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostExecute(List<Genie> genies) {
if (genies == null) {
new ArrayList<Genie>(); // "THERE WAS AN ERROR"
} else {
progressBar.setVisibility(View.GONE);
Log.i("INFO", genies.get(0).name);
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
genieAdapter=new GenieAdapter(getApplicationContext(),R.layout.genie_list, genies);
ListView list=(ListView)findViewById(R.id.listViewMain);
list.setAdapter(genieAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Test.this, "" + position, Toast.LENGTH_SHORT).show();
// if (position == 1) {
// startActivity(new Intent(Test.this, viewGenie1.class));
// }
}
});
list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("name", "%s");
intent.putExtra("add", "%s");
intent.putExtra("phn", "%s");
intent.putExtra("sal", "%s");
intent.putExtra("lea", "%s");
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
private String getRow(Genie g) {
return String.format("%s, %s, %s, %s, %s", g.name, g.salary, g.contact, g.paid_leaves, g.address);
}
}
}
Here's the viewGenie1.class:-
public class viewGenie1 extends AppCompatActivity implements View.OnClickListener {
TextView name;
EditText address, contact, salary, leaves;
Button attendance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_genie1);
name = (TextView) findViewById(R.id.txName);
address = (EditText) findViewById(R.id.txAddress);
contact = (EditText) findViewById(R.id.txContact);
salary = (EditText) findViewById(R.id.txSalary);
leaves = (EditText) findViewById(R.id.txLeaves);
Button update=(Button)findViewById(R.id.btUpdate);
update.setOnClickListener(this);
Button delete=(Button)findViewById(R.id.delete);
delete.setOnClickListener(this);
Button attendance = (Button) findViewById(R.id.attendance);
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAtt();
}
});
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
}
#Override
public void onClick(View view) {
final AlertDialog.Builder builder=new AlertDialog.Builder(viewGenie1.this);
builder.setMessage("Are you sure you want to delete records?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
new deleteTask().execute();
Toast.makeText(viewGenie1.this, "Genie deleted..!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(viewGenie1.this, navDrawer.class));
// GenieService genieService=new GenieService();
// genieService.delete(2);
// Log.d("Information", String.valueOf(genieService.delete(2)));
// Log.i("INFO", genies.get(0).name);
// startActivity(new Intent(viewGenie1.this,Test.class));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
private class deleteTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
GenieService genieService = new GenieService();
return genieService.delete(6);
}
}
public void showAtt() {
Intent intent = new Intent(this, viewAbsentee.class);
startActivity(intent);
}
}
Here's the xml file of the profile page I have created with hard coded values but want to display the actual values from the local mysql database using an API call:-
<LinearLayout 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"
android:background="#drawable/bcak"
tools:context="com.codionics.geniem.AddGenie"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="313dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/gradientbackground"
android:orientation="vertical">
<ImageView
android:layout_width="117dp"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/genie" />
<TextView
android:id="#+id/txName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Abc"
android:textColor="#ffffff"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="115dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="175dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:textColor="#f000"
android:textStyle="bold"
android:textSize="20sp" />
<EditText
android:id="#+id/txContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="123456789"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#f000"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="#+id/txAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Pune"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<LinearLayout
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_attach_money_black_24dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Paid leaves : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txLeaves"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:layout_weight="1"
android:text=" 5" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_money" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Salary : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txSalary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:text=" 5000"
android:textColor="#123" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/btUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="30dp"
android:background="#drawable/buttonstylegradient"
android:text="Update Genie"
android:textColor="#fff" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="80dp"
android:layout_marginTop="-50dp"
android:background="#drawable/buttonstylegradient"
android:text="Delete Genie"
android:textColor="#fff" />
<Button
android:id="#+id/attendance"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/buttonstylegradient"
android:textColor="#fff"
android:text="Attendance" />
</LinearLayout>
I want to display the details in the a profile page like this:-
profile page
Please pass the value in Intent using putExtra()
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("key","Value"); //Key must be unique and value should be the value which you want to pass to viewGenie1 class.
startActivity(intent);
In viewGenie1 class you can get the value like this
String value="";
if(getIntent().hasExtra("key")) {
value = getIntent().getExtras().getString("key");
}
Please replace
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
To
String mName = "",mAdd="",mPhn="",mSal="",mLea="";
if (getIntent().hasExtra("name")) {
mName = getIntent().getExtras().getString("name");
mAdd = getIntent().getExtras().getString("add");
mPhn = getIntent().getExtras().getString("phn");
mSal = getIntent().getExtras().getString("sal");
mLea = getIntent().getExtras().getString("lea");
}
name.setText(mName);
address.setText(mAdd);
contact.setText(mPhn);
salary.setText(mSal);
leaves.setText(mLea);

Button in custom dialog has no function

i have an issue related to customdialog.The Button in custom dialog has no function. setting_dialog.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="25px"
android:background="#color/exitdialog_background">
<TextView
android:id="#+id/setting_title"
android:layout_height="32dp"
android:layout_width="match_parent"
android:text="Setting"
android:textSize="20dp"
android:textColor="#color/While"
android:paddingTop="4dp"
android:background="#ff40c4ff"
android:typeface="sans"
android:textStyle="bold"
android:gravity="center" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_below="#+id/setting_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp">
<Switch
android:id="#+id/volume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:checked="true"
android:textSize="10sp" />
<TextView
android:id="#+id/txtVolume"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:text="Volume"
android:textColor="#color/While"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/linearLayoutBtns"
android:layout_below="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp">
<Button
android:id="#+id/btnSave"
android:layout_width="125dp"
android:layout_height="35dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:background="#drawable/button_selector"
android:gravity="center"
android:text="Save"
android:textColor="#color/While"
android:textSize="14dp"
android:textStyle="bold"
android:typeface="sans" />
</LinearLayout>
Setting class
public class SettingDialog extends Dialog implements View.OnClickListener
{
private Activity c;
private Button btnSave;
private TextView txtTitle;
private int layoutResID;
private OnSettingDialogClickListener mSaveClickListener;
public static interface OnSettingDialogClickListener {
public void onClick(SettingDialog settingDialog);
}
public SettingDialog(Activity a, int layoutResID) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
this.layoutResID = layoutResID;
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(layoutResID);
btnSave = (Button) findViewById(R.id.btnSave);
txtTitle = (TextView) findViewById(R.id.setting_title);
this.setCancelable(true);
this.setCanceledOnTouchOutside(false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setCancelable(Boolean cancelable)
{
this.setCancelable(cancelable);
}
public void setTitle(String title) {
this.txtTitle.setText(title);
}
public SettingDialog setSaveClickListener(String textName, OnSettingDialogClickListener listener) {
mSaveClickListener = listener;
btnSave.setText(textName);
return this;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
if (mSaveClickListener != null) {
mSaveClickListener.onClick(SettingDialog.this);
}
break;
default:
break;
}
}
}
Call Setting custom dialog
private void ShowSetting() {
SettingDialog settingDialog = new SettingDialog(PlayActivity.this, R.layout.setting_dialog);
settingDialog.setTitle("Setting");
settingDialog.setSaveClickListener("Save", new SettingDialog.OnSettingDialogClickListener() {
#Override
public void onClick(SettingDialog sDialog) {
LogHelper.d("PlayActivity", " Save button ");
sDialog.dismiss();
}
});
settingDialog.show();
}
Setting custom dialog apear and i touch save button but it has no function.
Could you please help me?
Woa, i've just found solution
Mising : btnSave.setOnClickListener(this);

setOnClickListener on a TextView inside a Cardview

I'm having some trouble implementing a setOnClickListener on a TextView inside a Cardview.I use this Cardview to populate a recicleview.
I have tried setting up the listener in the onBindViewHolder,but i can't see the log.
Single Item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:clickable="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/fotoUser"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true"
android:background="#f9fbff"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:minHeight="300dp" />
<LinearLayout
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_below="#+id/fotoUser"
android:weightSum="1"
android:background="#color/colorPrimary"
android:gravity="center_horizontal">
<ImageView
android:src="#drawable/ic_diaf"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/imageView2"
android:layout_weight="0.03"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="1.0"
android:id="#+id/txtDiaf"
android:paddingTop="0dp"
android:paddingRight="5dp"
android:textColor="#ffffff"
android:layout_gravity="center" />
<ImageView
android:src="#drawable/ic_tempi"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/imageView3"
android:layout_weight="0.03"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="1sec"
android:id="#+id/txtTempo"
android:paddingTop="0dp"
android:paddingRight="5dp"
android:textColor="#ffffff"
android:layout_gravity="center" />
<ImageView
android:src="#drawable/ic_iso"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/imageView4"
android:layout_weight="0.03"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="100"
android:id="#+id/txtIso"
android:paddingTop="0dp"
android:paddingRight="5dp"
android:textColor="#ffffff"
android:layout_gravity="center" />
<ImageView
android:src="#drawable/ic_fl"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/imageView5"
android:layout_weight="0.03"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="100mm"
android:id="#+id/txtFl"
android:paddingTop="0dp"
android:textColor="#ffffff"
android:layout_gravity="center" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="USERNAME"
android:id="#+id/userName"
android:clickable="true"
android:textStyle="bold|italic"
android:paddingTop="4dp"
android:paddingLeft="2dp"
android:layout_below="#+id/linear"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DESCRIZIONE"
android:id="#+id/descFoto"
android:paddingTop="4dp"
android:paddingLeft="2dp"
android:background="#color/colorPrimary"
android:paddingBottom="3dp"
android:layout_below="#+id/userName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#color/abc_primary_text_material_dark" />
<ImageView
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:src="#drawable/ic_like"
android:layout_toLeftOf="#+id/likes"
android:layout_alignTop="#+id/descFoto"
android:layout_alignBottom="#+id/descFoto" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NL"
android:id="#+id/likes"
android:paddingTop="4dp"
android:background="#color/colorPrimary"
android:paddingBottom="3dp"
android:layout_below="#+id/userName"
android:textColor="#color/abc_primary_text_material_dark"
android:layout_above="#+id/spazio"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="2dp"
android:id="#+id/spazio"
android:background="#color/colorPrimaryDark"
android:layout_below="#+id/descFoto"
android:layout_alignParentLeft="true"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="70dp"
android:id="#+id/btnLIKE"
android:clickable="true"
android:src="#drawable/ic_nolike"
android:layout_gravity="bottom"
android:adjustViewBounds="true"
android:paddingBottom="3dp"
android:layout_weight="0.06"
android:layout_above="#+id/linear"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
List->
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="5dp"
android:background="#fffffc">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listaFoto"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:dividerHeight="0dp"
android:divider="#fff9fa" /></RelativeLayout>
Bind->
public void onBindViewHolder(final SeguitiFragment_FotoADP.FotoViewHolder holder,final int position) {
SeguitiFragment_Foto fotoS = foto.get(position);
//.....
holder.nomeUser.setText(fotoS.getUser());
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
//.........
}
Adapter->
public class SeguitiFragment_FotoADP extends RecyclerView.Adapter<SeguitiFragment_FotoADP.FotoViewHolder>{
private List<SeguitiFragment_Foto> foto;
private Context c;
private String NomeFile;
public SeguitiFragment_FotoADP(List<SeguitiFragment_Foto> foto,Context c) {
this.foto = foto;
this.c=c;
}
#Override
public SeguitiFragment_FotoADP.FotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_subfoto, parent, false);
return new FotoViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SeguitiFragment_FotoADP.FotoViewHolder holder,final int position) {
SeguitiFragment_Foto fotoS = foto.get(position);
if(fotoS.getDiaframma()==-1){
holder.diaf.setText("--");
}else{
holder.diaf.setText(fotoS.getDiaframma()+"");
}
if(fotoS.getIso()==-1){
holder.iso.setText("--");
}else{
holder.iso.setText(fotoS.getIso()+"");
}
holder.nomeUser.setText(fotoS.getUser());
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
holder.desc.setText(fotoS.getDescrizione());
holder.tempo.setText(fotoS.getTempi()+ "sec");
holder.fl.setText(fotoS.getMillimetri()+"mm");
NomeFile=fotoS.getIdFoto();
File file = new File (c.getFilesDir(), NomeFile+".jpg");
if (!file.exists ()) {
downloadFTP ftp = new downloadFTP(fotoS.getIdFoto(), holder);
ftp.execute();
}else{
settaImmagine(holder);
}
}
#Override
public int getItemCount() {
return foto.size();
}
public static class FotoViewHolder extends RecyclerView.ViewHolder {
public ImageView immagine;
public TextView nomeUser;
public TextView desc;
public TextView diaf;
public TextView tempo;
public TextView iso;
public TextView fl;
public ImageView like;
public FotoViewHolder(View convertView) {
super(convertView);
nomeUser=(TextView)convertView.findViewById(R.id.userName);
desc=(TextView)convertView.findViewById(R.id.descFoto);
immagine=(ImageView)convertView.findViewById(R.id.fotoUser);
diaf=(TextView)convertView.findViewById(R.id.txtDiaf);
iso=(TextView)convertView.findViewById(R.id.txtIso);
fl=(TextView)convertView.findViewById(R.id.txtFl);
tempo=(TextView)convertView.findViewById(R.id.txtTempo);
like=(ImageView) convertView.findViewById(R.id.btnLIKE);
}
public void settaImmagine(FotoViewHolder v){
File file = new File(c.getFilesDir(), NomeFile + ".jpg");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
v.immagine.setImageBitmap(bitmap);
}
}
Thank You!
Try to set onClickListener after setText on your onBindViewHolder.
Refer this.
holder.mTextView.setText(mValues.get(position));
holder.mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click", "Effettuato");
}
});
As per your code change this.
holder.nomeUser.setText(fotoS.getUser());
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
EDIT 1:
In your FotoViewHolder overRide this before settaImmagine function.
#Override
public String toString() {
return super.toString() + " '" + nomeUser.getText();
}
Use
in xml
<TextView
<-- other attributes -->
android:clickable="true"
/>
in Adapter
nomeUser= (TextView)view.findViewById(R.id.**id**);
and finally
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
Inside your
class FotoViewHolder
nomUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
if you want to identify different nomUser ,you can get the adapter position by using this code
int pos = getAdapterPosition();
This is your TextView in your layout :
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="USERNAME"
android:id="#+id/userName"
android:textStyle="bold|italic"
android:paddingTop="4dp"
android:paddingLeft="2dp"
android:layout_below="#+id/linear"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
You don't have android:clickable="true" . Add android:clickable="true" to your required TextView
and in your onBindViewHolder add :
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","clicked");
}
});
First add below property in you parent(Means parent Linear-layout of your singleItem) of Single Item layout,
android:descendantFocusability="blocksDescendants"
and then try as below,
public void onBindViewHolder(final SeguitiFragment_FotoADP.FotoViewHolder holder,final int position)
{
SeguitiFragment_Foto fotoS = foto.get(position);
bind(position,fotoS);
}
now in your FotoViewHolder class make method as below,
public void bind(int pos, SeguitiFragment_Foto fotoS) {
nomeUser.setText(fotoS.getUser());
nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Click","Effettuato");
}
});
}

Code optimisation. (Architecture)

I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
The question is: how to optimize my code, I don't like how it's look like? If I decide to add some more options it wouldn't be readable.
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString().toLowerCase();
String t2 = et_one_two.getText().toString().toLowerCase();
String t3 = et_one_three.getText().toString().toLowerCase();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
});
}
}
In my Layout I use ScrollView:
<LinearLayout 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=".MainActivity"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/task1"
android:id="#+id/textView1"
android:textSize="20sp"
android:textColor="#010101" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_one"
android:id="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_one"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_two"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_two"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_three"
android:id="#+id/textView4" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_three"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_four"
android:id="#+id/textView5" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_four"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_five"
android:id="#+id/textView6" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_five"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/buttonCheck" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
I would strongly suggest a nice library called Butterknife by JakeWharton :
http://jakewharton.github.io/butterknife/
In your case your code would look like this :
public class MainActivity extends AppCompatActivity {
#Bind(R.id.et_one_one) EditText et_one_one;
#Bind(R.id.et_one_two) EditText et_one_two;
#Bind(R.id.et_one_three) EditText et_one_three;
#Bind(R.id.buttonCheck) Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
...
}
#OnClick(R.id.submit)
public void submit(View view) {
// check code here
}
Also you can group all your edit texts in a group :
#Bind({ R.id.et_one_one, R.id.et_one_two, R.id.et_one_three })
List<EditText> nameViews;
And apply some setters or actions on them :
...
ButterKnife.apply(nameViews, LOWERCASE);
...
static final ButterKnife.Action<View> LOWERCASE= new ButterKnife.Action<View>() {
#Override public void apply(View view, int index) {
// TODO set the text of the view to lowercase and disable textview
}
};
You can use RecyclerView to implement this. With it, you can dynamically add as much EditText for cars as you want. The sample is shown as below:
In your Activity:
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] answerArray;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
answerArray = new String[]{
"maserati",
"mercedes",
"bmw"
... (you can add as much as you want)
}
buttonCheck = (Button) findViewById(R.id.buttonCheck);
}
For RecyclerView.Adapter
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
String[] mAnswerArray;
public static class ViewHolder extends RecyclerView.ViewHolder {
public EditText editText;
public ViewHolder(View v) {
super(v);
editText = (EditText) v.findViewById(R.id.editText);
}
}
public MyRecyclerAdapter(String[] answerArray) {
this.mAnswerArray = answerArray;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position){
super.onBindViewHolder(holder, position);
final String answer = mAnswerArray.get(position);
if ( holder.editText.getText().toString().toLowerCase().equals(answer) ) {
holder.editText.setBackgroundColor(Color.GREEN);
} else {
holder.editText.setBackgroundColor(Color.RED);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemCount() {
return mAnswerArray.size();
}
}
For "my_list_item.xml", you just need to put inside and as for the ButtonCheck you can also pass an array or flag into adapter to record the state of each answer (correct or wrong) in order to decide whether to go to SecondActivity.

Categories

Resources