I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I don´t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.
The image moves perfectly the first time into its place i.e detail activity image view and also returns perfectly back to the main activity but when I click the same image next time the transition animation moves the image to an incorrect (too high) offset in the detail activity and once the animation completes the image will appear to "warp" into the correct position.
Here is my DetailActivity.java file:
package com.akshitjain.popularmovies;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
postponeEnterTransition();
}
ImageView backdropImageView = (ImageView) findViewById(R.id.detail_image_view);
final ImageView posterImageView = (ImageView) findViewById(R.id.detail_poster);
TextView overviewTextView = (TextView) findViewById(R.id.overview_text_view);
TextView releaseDateTextView = (TextView) findViewById(R.id.release_date);
TextView userRatingTextView = (TextView) findViewById(R.id.user_rating);
TextView genreTextView = (TextView) findViewById(R.id.genre);
genreTextView.setText("");
Genre genreObject = new Genre();
String genreName;
Intent intent = getIntent();
if (intent != null && intent.hasExtra(Constants.MOVIE_OBJECT_PARCELABLE_EXTRA)) {
Movies movies = intent.getParcelableExtra(Constants.MOVIE_OBJECT_PARCELABLE_EXTRA);
int[] genre;
genre = movies.genre;
for (int i = 0; i < genre.length; ++i) {
genreName = genreObject.getGenreName(genre[i]);
genreTextView.append(genreName);
if (i < genre.length - 1) {
genreTextView.append(", ");
}
}
setTitle(movies.originalTitle);
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_LARGE).trim() + movies.backdropPath)
.into(backdropImageView);
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_SMALL).trim() + movies.posterPath)
.into(posterImageView, new Callback() {
#Override
public void onSuccess() {
posterImageView.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
posterImageView.getViewTreeObserver().removeOnPreDrawListener(this);
startPostponedEnterTransition();
}
return true;
}
}
);
}
#Override
public void onError() {
}
}
);
overviewTextView.setText(movies.overview);
releaseDateTextView.setText(movies.releaseDate);
userRatingTextView.setText(movies.userRating);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#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_detail, 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();
switch (id) {
case android.R.id.home:
supportFinishAfterTransition();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this.
posterImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_SMALL).trim() + movies.posterPath)
.into(posterImageView, new Callback() {
#Override
public void onSuccess() {
startPostponedEnterTransition();
}
#Override
public void onError() {
}
});
}
}
package com.example.artru_000.question;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class questioninterface extends ActionBarActivity {
public static final int QUESTIONS_LENGTH = 50;
public void setQuestion() {
for (Questions e : Questions.values()) {
if (random(QUESTIONS_LENGTH) == e.order) {
currentQuestion = e.question;
correctAnswer = e.correctAnswer;
answer1 = e.answer1;
answer2 = e.answer2;
clearWidgetsText();
setWidgetsText();
return;
}
}
}
public void clearWidgetsText() {
firstAnswer.setText("");
secondAnswer.setText("");
thirdAnswer.setText("");
question.setText("");
}
public void setWidgetsText() {
question.setText(currentQuestion);
switch (random(2)) {
case 0:
firstAnswer.setText(correctAnswer);
secondAnswer.setText(answer1);
thirdAnswer.setText(answer2);
break;
case 1:
thirdAnswer.setText(correctAnswer);
secondAnswer.setText(answer1);
firstAnswer.setText(answer2);
break;
case 2:
secondAnswer.setText(correctAnswer);
firstAnswer.setText(answer1);
thirdAnswer.setText(answer2);
break;
}
}
Random rand = new Random();
String currentQuestion, correctAnswer, answer1, answer2;
public int random(int range) {
return rand.nextInt(range);
}
Button getQuestion;
Button firstAnswer;
Button secondAnswer;
Button thirdAnswer;
TextView answerStatus;
TextView question;
public void setAnswerStatus(String status) {
if(status.equalsIgnoreCase("Right")) {
answerStatus.setText("Right");
answerStatus.setTextColor(Color.GREEN);
}
if(status.equalsIgnoreCase("wrong")) {
answerStatus.setText("Wrong");
answerStatus.setTextColor(Color.RED);
}
}
public void buttonPushes() {
getQuestion.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setQuestion();
return;
}
});
firstAnswer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(firstAnswer.getText().toString().equalsIgnoreCase(correctAnswer)) {
setAnswerStatus("right");
setQuestion();
return;
} else {
setAnswerStatus("wrong");
setQuestion();
return;
}
}
});
secondAnswer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(secondAnswer.getText().toString().equalsIgnoreCase(correctAnswer)) {
setAnswerStatus("right");
setQuestion();
return;
} else {
setAnswerStatus("wrong");
setQuestion();
return;
}
}
});
thirdAnswer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(thirdAnswer.getText().toString().equalsIgnoreCase(correctAnswer)) {
setAnswerStatus("right");
setQuestion();
return;
} else {
setAnswerStatus("wrong");
setQuestion();
return;
}
}
});
}
private void construct() {
getQuestion = (Button) findViewById(R.id.get_question);
firstAnswer = (Button) findViewById(R.id.answer1);
secondAnswer = (Button) findViewById(R.id.answer2);
thirdAnswer = (Button) findViewById(R.id.answer3);
answerStatus = (TextView) findViewById(R.id.wrongright);
question = (TextView) findViewById(R.id.question);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questioninterface);
construct();
buttonPushes();
}
#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_questioninterface, 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);
}
}
The code above is like a trivia game. When you click the getQuestion button, you get a question and three buttons with 3 different answers. If you click the right button, it says it's right and gives you another questions. If you answer wrong, it says it's wrong and gives you another question. It works. The problem is, however, that sometimes i need to click the button several times in order to get the other question and the other answers. Any ideas?
Have you tried adding breakpoints to your code and running it in debug mode to pin-point where the weirdness is happening? Add breakpoints to your button clicks, where you decide what to do, where you output info and so on. If you have, tell us what you see.
Supposedly i have 3 checkboxes, Each checkboxes has a corresponding string value. What i want is that when i check checkbox 1 and 2, their corresponding strings or value will be all put over a edittext.
Example:
[✓] Checkbox 1 (Egg)
[✓] Checkbox 2 (Hotdog)
[ ] Checkbox 3 (Cheese)
When I check boxes 1 and 2. It will go to edittext and view as "Egg"\n + "Hotdog" or similar.
Output:
Edittext:
Egg
Hotdog
Is that possible? Thanks for your help!
package com.example.checkboxes;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private CheckBox egg, hotdog, cheese;
private OnClickListener checkboxclicklistener;
private EditText display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
egg = (CheckBox) findViewById(R.id.a);
cheese = (CheckBox) findViewById(R.id.c);
hotdog = (CheckBox) findViewById(R.id.b);
display = (EditText) findViewById(R.id.display);
createListener(egg);
createListener(hotdog);
createListener(cheese);
}
public void createListener(CheckBox checkbox) {
checkbox.setOnClickListener( new OnClickListener() {
StringBuilder checkeditems = new StringBuilder();
#Override
public void onClick(View v) {
//is checkbox checked?
if (((CheckBox) v).isChecked()) {
String checkboxname = ((CheckBox) v).getText().toString();
Toast.makeText(getApplicationContext(), checkboxname, Toast.LENGTH_LONG).show();
if(checkboxname.equalsIgnoreCase("egg"))
{
display.setText(display.getText().toString()+"\nEgg");
}
else if(checkboxname.equalsIgnoreCase("hotdog"))
{
display.setText(display.getText().toString()+"\nHotdog");
}
else if(checkboxname.equalsIgnoreCase("cheese"))
{
display.setText(display.getText().toString()+"\nCheese");
}
}
else if (((CheckBox) v).isChecked()==false)
{
String checkboxname = ((CheckBox) v).getText().toString();
if(checkboxname.equalsIgnoreCase("egg"))
{
display.setText(display.getText().toString().replace("\nEgg", ""));
}
else if(checkboxname.equalsIgnoreCase("hotdog"))
{
display.setText(display.getText().toString().replace("\nHotdog", ""));
}
else if(checkboxname.equalsIgnoreCase("cheese"))
{
display.setText(display.getText().toString().replace("\nCheese", ""));
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You could use setOnClickListener like so
CheckBox chkEgg;
EditText yourEditText;
String yourText;
public void addListenerOnChkIos() {
chkEgg = (CheckBox) findViewById(R.id.checkbox1);
chkEgg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkEgg checked?
if (((CheckBox) v).isChecked()) {
yourText = yourText + "Egg";
yourEditText.setText(yourText);
}
}
});
}
I only did it for one
Hope this helps
package com.thenewboston.jordy;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Startingpoint extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startingpoint);
}
int counter;
Button add, sub;
TextView display;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.startingpoint, menu);
return true;
counter = 0;
add = (Button) findViewById(R.id.BAdd);
sub = (Button) findViewById(R.id.Bsub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
}
}
hello,
i just started following tutorial to make android apps with eclips.
Now I get this error unreachable code at the line with "counter = 0"
I think it's has to do something with the line "return true" because, when i remove that the error is gone but then i get other errors :s, does someone know what the problem is here?
Thanks in advance
Any code after the return will never be executed. Therefore you get unreachable code.
Put return at the end of the method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startingpoint, menu);
counter = 0;
...
return true;
}