Can we define a function in OnCreate method which can be used to initialize buttons and all other widgets. I have tried the following but I am getting
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a
null object reference error
package com.conceptkillers.www.electromania1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
/**
* Created by Nikesh on 11/02/2016.
*/
public class OhmsLawActivity extends AppCompatActivity {
int checkedCount = 0;
LinearLayout vlayout,ilayout,rlayout,playout;
CheckBox checkBox1,checkBox2,checkBox3,checkBox4;
Spinner spinnerV,spinnerI,spinnerR,spinnerP;
EditText edittextv,edittexti,edittextr,edittextp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setTitle("Ohms Law");
InitializeAllWidgets();
}
public void InitializeAllWidgets() {
checkBox1 = (CheckBox) findViewById(R.id.checkbox_v);
checkBox2 = (CheckBox) findViewById(R.id.checkbox_i);
checkBox3 = (CheckBox) findViewById(R.id.checkbox_r);
checkBox4 = (CheckBox) findViewById(R.id.checkbox_p);
edittextv = (EditText) findViewById(R.id.edittext_v);
edittexti = (EditText) findViewById(R.id.edittext_i);
edittextr = (EditText) findViewById(R.id.edittext_r);
edittextp = (EditText) findViewById(R.id.edittext_p);
String[] valuesVoltageSpinner = {"YV","ZV","EV","PV","TV","GV","MV","KV"
,"V","mV","uV","nV","pV","fV","aV","zV","yV"};
String[] valuesCurrentSpinner = {"YA","ZA","EA","PA","TA","GA","MA","KA"
,"A","mA","uA","nA","pA","fA","aA","zA","yA"};
String[] valuesResistanceSpinner = {"YOhm","ZOhm","EOhm","POhm","TOhm","GOhm","MOhm","KOhm"
,"Ohm","mOhm","uOhm","nOhm","pOhm","fOhm","aOhm","zOhm","yOhm"};
String[] valuesPowerSpinner = {"YW","ZW","EW","PW","TW","GW","MW","KW"
,"W","mW","uW","nW","pW","fW","aW","zW","yW"};
spinnerV = (Spinner) findViewById(R.id.spinner_v);
spinnerI = (Spinner) findViewById(R.id.spinner_i);
spinnerR = (Spinner) findViewById(R.id.spinner_r);
spinnerP = (Spinner) findViewById(R.id.spinner_p);
ArrayAdapter<String> voltageAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, valuesVoltageSpinner);
voltageAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerV.setAdapter(voltageAdapter);
ArrayAdapter<String> currentAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, valuesCurrentSpinner);
currentAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerI.setAdapter(currentAdapter);
ArrayAdapter<String> resistanceAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, valuesResistanceSpinner);
resistanceAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerR.setAdapter(resistanceAdapter);
ArrayAdapter<String> powerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, valuesPowerSpinner);
powerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerP.setAdapter(powerAdapter);
checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBox1();
}
});
checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBox2();
}
});
checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBox3();
}
});
checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBox4();
}
});
}
public void onButtonClicked(View v) {
switch(v.getId()) {
case R.id.simple_voltage:
checkBox1.setVisibility(v.INVISIBLE);
checkBox2.setVisibility(v.VISIBLE);
checkBox3.setVisibility(v.VISIBLE);
checkBox4.setVisibility(v.VISIBLE);
checkedCount = 0;
break;
case R.id.simple_current:
checkBox1.setVisibility(v.VISIBLE);
checkBox2.setVisibility(v.INVISIBLE);
checkBox3.setVisibility(v.VISIBLE);
checkBox4.setVisibility(v.VISIBLE);
checkedCount = 0;
break;
case R.id.simple_resistance:
checkBox1.setVisibility(v.VISIBLE);
checkBox2.setVisibility(v.VISIBLE);
checkBox3.setVisibility(v.INVISIBLE);
checkBox4.setVisibility(v.VISIBLE);
checkedCount = 0;
break;
case R.id.simple_power:
checkBox1.setVisibility(v.VISIBLE);
checkBox2.setVisibility(v.VISIBLE);
checkBox3.setVisibility(v.VISIBLE);
checkBox4.setVisibility(v.INVISIBLE);
checkedCount = 0;
break;
}
}
private void handleCheckBox1() {
if(checkedCount < 2) {
if (checkBox1.isChecked()) {
checkedCount++;
edittextv.setVisibility(View.VISIBLE);
spinnerV.setVisibility(View.VISIBLE);
} else {
checkedCount--;
edittextv.setVisibility(View.INVISIBLE);
spinnerV.setVisibility(View.INVISIBLE);
}
}
}
private void handleCheckBox2() {
if(checkedCount < 2) {
if (checkBox2.isChecked()) {
checkedCount++;
edittexti.setVisibility(View.VISIBLE);
spinnerI.setVisibility(View.VISIBLE);
} else {
checkedCount--;
edittexti.setVisibility(View.INVISIBLE);
spinnerI.setVisibility(View.INVISIBLE);
}
}
}
private void handleCheckBox3() {
if(checkedCount < 2) {
if (checkBox3.isChecked()) {
checkedCount++;
edittextr.setVisibility(View.VISIBLE);
spinnerR.setVisibility(View.VISIBLE);
} else {
checkedCount--;
edittextr.setVisibility(View.INVISIBLE);
spinnerR.setVisibility(View.INVISIBLE);
}
}
}
private void handleCheckBox4(){
if(checkedCount < 2) {
if (checkBox4.isChecked()) {
checkedCount++;
edittextp.setVisibility(View.VISIBLE);
spinnerP.setVisibility(View.VISIBLE);
} else {
checkedCount--;
edittextp.setVisibility(View.INVISIBLE);
spinnerP.setVisibility(View.INVISIBLE);
}
}
}
}
You missed the setContentView
setContentView(R.layout.main)
You have not set any layout to your activity. Use setContentView(int layoutId) in your code which will attach the layout to which these widgets (spinners) belong.
The rest of the code seems fine. And by that I mean you can have a method that initializes the widgets.
Change your code and add your layout
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContectView(R.layout.view);
this.setTitle("Ohms Law");
InitializeAllWidgets();
}
Related
I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}
The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java
I have an issue updateing TextView in Android App.What I do is, when "+" button is pressed, RecycleView opens, then I click on the item retrived there from Kinvey.Then I pass name of the item Clicked to the Main activity.From Main activity i can LOG that data when I run the app for the seckond time (First time value is null since i did not clicked an item in RecycleView), but I can not set TextView with that Value(TextView stay empty)?3rd time when i run the app, retrived value is null again.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Testiraj";
private RecyclerView rv;
public Context context;
private TextView TextViewGymName;
private TextView TextViewVisitorsNumber;
private List<AllGyms> mVisitors;
public static final String MY_PREFS_NAME = "MyPrefsFile";
public String mRVPickedItem;
public String restoredText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextViewGymName = (TextView) findViewById(R.id.gymName);
TextViewVisitorsNumber = (TextView) findViewById(R.id.gymVisitors);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
restoredText = prefs.getString("name", "nothing");
if(restoredText!=null){
Log.v(TAG,restoredText);
TextViewGymName.setText(restoredText);
}
else{
Log.v(TAG, "null" +" "+ restoredText);
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Intent intenti=getIntent();
Bundle b = intenti.getExtras();
if(b!=null){
mRVPickedItem = (String) b.get("NAME_OF_THE_STRING");
final Client mKinveyClient = new Client.Builder("KEY", "KEY_APP"
, this.getApplicationContext()).build();
final Query query = new Query();
query.equals("name", mRVPickedItem);
query.equals("visitors");
AsyncAppData<AllGyms> searchedEvents = mKinveyClient.appData("allGyms", AllGyms.class);
searchedEvents.get(query, new KinveyListCallback<AllGyms>() {
#Override
public void onSuccess(AllGyms[] event) {
ArrayList<AllGyms> arrayList = new ArrayList<AllGyms>(Arrays.asList(event));
String[] array = new String[arrayList.size()];
mVisitors = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
array[i] = arrayList.get(i).getVisitors();
//allGymses.add(new AllGyms(test[i].getName()));
//Log.v(TAG, "received " + array[i]);
TextViewVisitorsNumber.setText(array[i]);
}
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to query ", error);
}
});
}
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", mRVPickedItem);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
restoredText = prefs.getString("name", mRVPickedItem);
TextViewGymName.setText(restoredText);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, `RecyclerViewActivity.class);`
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass method first
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RecycleView Activity:
package com.fittoloc.uros.gymloced;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.Client;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.android.callback.KinveyUserCallback;
import com.kinvey.java.Query;
import com.kinvey.java.User;
import com.kinvey.java.core.KinveyClientCallback;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RecyclerViewActivity extends AppCompatActivity {
private List<AllGyms> allGymses;
private RecyclerView rv;
public Context context;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
rv=(RecyclerView)findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeRecycleView();
rv.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
})
);
}
private void initializeRecycleView() {
//ovde resiti problem!!!!
final Client mKinveyClient = new Client.Builder("KEY", "KEY"
, this.getApplicationContext()).build();
mKinveyClient.user().login(new KinveyUserCallback() {
#Override
public void onFailure(Throwable t) {
CharSequence text = "Login error.";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(User u) {
CharSequence text = "Welcome back!";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
final AllGyms teretane = new AllGyms();
Query myQuery = mKinveyClient.query();
myQuery.equals ("name");
AsyncAppData<AllGyms> myGyms = mKinveyClient.appData("allGyms", AllGyms.class);
myGyms.get(myQuery, new KinveyListCallback<AllGyms>() {
#Override
public void onSuccess(AllGyms[] results) {
ArrayList <AllGyms> arrayList = new ArrayList<AllGyms>(Arrays.asList(results));
String [] array = new String[arrayList.size()];
allGymses = new ArrayList<>();
for(int i = 0 ; i < arrayList.size() ; i++){
array[i] = arrayList.get(i).getName();
//allGymses.add(new AllGyms(test[i].getName()));
allGymses.add((new AllGyms(array[i])));
//Log.v(TAG, "received " + array[i]);
initializeAdapter();
}
//Log.v(TAG, "received " + results + " allGyms");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetchByFilterCriteria", error);
}
});
//
}
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(allGymses,context);
rv.setAdapter(adapter);
}
}
RecyleItemClickListener:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private static final String TAG = "MyActivity";
private String position;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
I am a beginner, When i add music files to Sd card the list view in my Music app isn't updating untill i reboot the device or my genymotion emulator. and the songs are also playing with lagging.
Here is my main Acivity.java code :
import com.techdsk.musicdsk.musicdsk.adapter.CustomAdapter;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
CustomAdapter customAdapter = null;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
ProgressBar progressBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if(PlayerConstants.SONGS_LIST.size() <= 0){
PlayerConstants.SONGS_LIST = UtilFunctions.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this,R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id){
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(),SongService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SongService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try{
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}else{
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}catch(Exception e){}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try{
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = UtilFunctions.getAlbumart(context, data.getAlbumId());
if(albumArt != null){
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
}catch(Exception e){}
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI(){
updateUI();
changeButton();
}
}
Here is my Audioplayer Activity.java Code :
package com.techdsk.musicdsk.musicdsk;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.controls.Controls;
import com.techdsk.musicdsk.musicdsk.service.SongService;
import com.techdsk.musicdsk.musicdsk.util.PlayerConstants;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class AudioPlayerActivity extends Activity {
Button btnBack;
static Button btnPause;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
ProgressBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.audio_player);
context = this;
init();
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
PlayerConstants.PROGRESSBAR_HANDLER = new Handler(){
#Override
public void handleMessage(Message msg){
Integer i[] = (Integer[])msg.obj;
textBufferDuration.setText(UtilFunctions.getDuration(i[0]));
textDuration.setText(UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI(){
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if(PlayerConstants.SONG_PAUSED){
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
}else{
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try{
String songName = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getTitle();
String artist = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getArtist();
String album = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbum();
String composer = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if(composer != null && composer.length() > 0){
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
}else{
textComposer.setVisibility(View.GONE);
}
}catch(Exception e){
e.printStackTrace();
}
try{
long albumId = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = UtilFunctions.getAlbumart(context, albumId);
if(albumArt != null){
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
}else{
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(UtilFunctions.getDefaultAlbumArt(context)));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
custom adapter .java code :
package com.techdsk.musicdsk.musicdsk.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.techdsk.musicdsk.musicdsk.R;
import com.techdsk.musicdsk.musicdsk.util.MediaItem;
import com.techdsk.musicdsk.musicdsk.util.UtilFunctions;
public class CustomAdapter extends ArrayAdapter<MediaItem>{
ArrayList<MediaItem> listOfSongs;
Context context;
LayoutInflater inflator;
public CustomAdapter(Context context, int resource, ArrayList<MediaItem> listOfSongs) {
super(context, resource, listOfSongs);
this.listOfSongs = listOfSongs;
this.context = context;
inflator = LayoutInflater.from(context);
}
private class ViewHolder{
TextView textViewSongName, textViewArtist, textViewDuration;
}
ViewHolder holder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
if(convertView == null){
myView = inflator.inflate(R.layout.custom_list, parent, false);
holder = new ViewHolder();
holder.textViewSongName = (TextView) myView.findViewById(R.id.textViewSongName);
holder.textViewArtist = (TextView) myView.findViewById(R.id.textViewArtist);
holder.textViewDuration = (TextView) myView.findViewById(R.id.textViewDuration);
myView.setTag(holder);
}else{
holder = (ViewHolder)myView.getTag();
}
MediaItem detail = listOfSongs.get(position);
holder.textViewSongName.setText(detail.toString());
holder.textViewArtist.setText(detail.getAlbum() + " - " + detail.getArtist());
holder.textViewDuration.setText(UtilFunctions.getDuration(detail.getDuration()));
return myView;
}
}
when you add the file you can use NotifyDatasetChanged(). this will tell your adapter to refresh its data. So when your source array is updated after adding a new file you can call NotifyDatasetChanged() method.
as Ex. if you have a method named Add() inside your adapter then.
public void Add (item e){
items.add (e);
NotifyDatasetChanged();
}
will refresh your data.
Your list is not getting updated because it is not informed about the data change,
the documentation in the ADW explains:
notifyDataSetChanged() Notifies the attached observers that the
underlying data has been changed and any View reflecting the data set
should refresh itself.
Solution
Notify yor adapter:
customAdapter.notifyDataSetChanged();
I am trying to add a basic setting to my app. I would like to change the hint of an EditText in one of my activities if the checkBox is unchecked.
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="PREF_SHOW_UNITS"
android:id="#+id/Check1"
android:title="Show units in Kinematics"
android:defaultValue="true" >
</CheckBoxPreference>
</PreferenceScreen>
SettingsActivity.java:
package com.supermath.jacobgb24.supermath;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import static com.supermath.jacobgb24.supermath.R.xml.preferences;
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(preferences);
}
}
Code that I am trying to add changes to:
public class Kinematics extends ActionBarActivity {
static EditText tval, aval, vval, xval;
static double a, t, x, v;
static DecimalFormat fmt = new DecimalFormat("###,###.###");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.klayout);
CheckBox cb1 = (CheckBox) findViewById(R.id.Check1);
tval = (EditText) findViewById(R.id.time);
aval = (EditText) findViewById(R.id.accel);
vval = (EditText) findViewById(R.id.velocity);
xval = (EditText) findViewById(R.id.xpos);
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkbox, boolean isChecked) {
if (isChecked) {
tval.setHint("YAY");
} else {
tval.setHint("UNYAY");
}
}
});
}
Solved
Since I was using preferences I needed the following code:
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean disp = prefs.getBoolean("PREF_SHOW_UNITS", true);
if(disp)
tval.setHint("t(s)");
tval.setHint("t(s)");
else if(!disp)
tval.setHint("UNYAY");
you can change the hint of the edittext on checkbox check via following:
your_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkbox,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked)
{
your_edittext.setHint(textonChecked);
}
else
{
your_edittext.setHint(textonUnchecked);
}
}
});
//Get EditText
EditText editText1 = (EditText) findViewById(R.id.editText1);
//Get Checkbox
CheckBox cb1 = (Checkbox) findViewById(R.id.checkBox1);
//Add Listener to Checkbox
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
//Set a hint to EditText
editText1.setHint("This is a hint!");
}
}
});