I am making android calculator. I made some functions but the first problem is double clickable operation.I tried but couldn't. when i click two operations consequently both are appearing on the text view. i'll post my code if you can solve double clickable operation problem please post your code on comment.
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private TextView _result;
private String display = "";
private String currentOperator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen = (TextView) findViewById(R.id.txtScreen);
_result = (TextView) findViewById(R.id.id_result);
}
public void updateScreen() {
_screen.setText(display);
}
public void onClickNumber(View v) {
Button b = (Button) v;
display += b.getText();
updateScreen();
}
public void onClickOperator(View v) {
Button b = (Button) v;
display += b.getText();
currentOperator = b.getText().toString();
updateScreen();
}
public void clear() {
display = "";
currentOperator = "";
}
public void onClickClear(View view) {
clear();
updateScreen();
}
public double operate(String a, String op, String b) {
switch (op) {
case "+":
return Double.valueOf(a) + Double.valueOf(b);
case "-":
return Double.valueOf(a) - Double.valueOf(b);
case "*":
return Double.valueOf(a) * Double.valueOf(b);
case "/":
return Double.valueOf(a) / Double.valueOf(b);
default:
return -1;
}
}
public void onClickEqual(View v) {
String[] operation = display.split(Pattern.quote(currentOperator));
_result.setText(String.valueOf(operate(operation[0], currentOperator, operation[1])));
}
}
what I understand from your question regarding double operation is that Let suppose you are performing operation of + and when you click again for + it gets displayed 2 times on textview (as your method updateScreen suggest). If that is the problem, you can do as mentioned below
public void updateScreen() {
if (screen.getText().toString().equalsIgnoreCase("")) {
screen.setText(display);
} else if (!display.equalsIgnoreCase(screen.getText().toString())) {
screen.setText("");
screen.setText(display);
} else {
//this is the case that means that operator is already set on the text
}
}
Hope that helps you.
Related
I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}
Hello Before starting this i would like to tell you that there are many topics with the similar title but my problem is different i am not able to change the orientation of the camera at all i have tried many things.
Following are my codes and its a live streaming project.
public class MainActivity extends Activity implements
OnClickListener,
RtspClient.Callback,
Session.Callback,
SurfaceHolder.Callback,
OnCheckedChangeListener {
public final static String TAG = "MainActivity";
private Button mButtonSave;
private Button mButtonVideo;
private ImageButton mButtonStart;
private ImageButton mButtonFlash;
private ImageButton mButtonCamera;
private ImageButton mButtonSettings;
private RadioGroup mRadioGroup;
private FrameLayout mLayoutVideoSettings;
private FrameLayout mLayoutServerSettings;
private SurfaceView mSurfaceView;
private TextView mTextBitrate;
private EditText mEditTextURI;
private EditText mEditTextPassword;
private EditText mEditTextUsername;
private ProgressBar mProgressBar;
private Session mSession;
private RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mButtonVideo = (Button) findViewById(R.id.video);
mButtonSave = (Button) findViewById(R.id.save);
mButtonStart = (ImageButton) findViewById(R.id.start);
mButtonFlash = (ImageButton) findViewById(R.id.flash);
mButtonCamera = (ImageButton) findViewById(R.id.camera);
mButtonSettings = (ImageButton) findViewById(R.id.settings);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mEditTextURI = (EditText) findViewById(R.id.uri);
mEditTextUsername = (EditText) findViewById(R.id.username);
mEditTextPassword = (EditText) findViewById(R.id.password);
mTextBitrate = (TextView) findViewById(R.id.bitrate);
mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
mRadioGroup = (RadioGroup) findViewById(R.id.radio);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.setOnClickListener(this);
mButtonStart.setOnClickListener(this);
mButtonSave.setOnClickListener(this);
mButtonFlash.setOnClickListener(this);
mButtonCamera.setOnClickListener(this);
mButtonVideo.setOnClickListener(this);
mButtonSettings.setOnClickListener(this);
mButtonFlash.setTag("off");
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
if (mPrefs.getString("uri", null) != null) mLayoutServerSettings.setVisibility(View.GONE);
mEditTextURI.setText(mPrefs.getString("uri", "default_stream"));
mEditTextPassword.setText(mPrefs.getString("password", ""));
mEditTextUsername.setText(mPrefs.getString("username", ""));
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000,16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(90)//I tried changing this value but nothing happened it works even if i comment this line.
.setCallback(this)
.build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
Camera camera;
mSurfaceView.getHolder().addCallback(this);
selectQuality();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
mLayoutVideoSettings.setVisibility(View.GONE);
mLayoutServerSettings.setVisibility(View.VISIBLE);
selectQuality();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mLayoutServerSettings.setVisibility(View.GONE);
toggleStream();
break;
case R.id.flash:
if (mButtonFlash.getTag().equals("on")) {
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash.setImageResource(R.drawable.ic_flash_off_holo_light);
mButtonFlash.setTag("on");
}
mSession.toggleFlash();
break;
case R.id.camera:
mSession.switchCamera();
break;
case R.id.settings:
if (mLayoutVideoSettings.getVisibility() == View.GONE &&
mLayoutServerSettings.getVisibility() == View.GONE) {
mLayoutServerSettings.setVisibility(View.VISIBLE);
} else {
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.GONE);
}
break;
case R.id.video:
mRadioGroup.clearCheck();
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.VISIBLE);
break;
case R.id.save:
mLayoutServerSettings.setVisibility(View.GONE);
break;
}
}
#Override
public void onDestroy(){
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
private void selectQuality() {
int id = mRadioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) findViewById(id);
if (button == null) return;
String text = button.getText().toString();
Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
int framerate = Integer.parseInt(matcher.group(3));
int bitrate = Integer.parseInt(matcher.group(4))*1000;
mSession.setVideoQuality(new VideoQuality(width, height, framerate, bitrate));
Toast.makeText(this, ((RadioButton)findViewById(id)).getText(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Selected resolution: "+width+"x"+height);
}
private void enableUI() {
mButtonStart.setEnabled(true);
mButtonCamera.setEnabled(true);
}
// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
mProgressBar.setVisibility(View.VISIBLE);
if (!mClient.isStreaming()) {
String ip,port,path;
// We save the content user inputs in Shared Preferences
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Editor editor = mPrefs.edit();
editor.putString("uri", mEditTextURI.getText().toString());
editor.putString("password", mEditTextPassword.getText().toString());
editor.putString("username", mEditTextUsername.getText().toString());
editor.commit();
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d*)/(.+)");
Matcher m = uri.matcher(mEditTextURI.getText()); m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
// mClient.setCredentials(mEditTextUsername.getText().toString(), mEditTextPassword.getText().toString());
mClient.setCredentials("umair", "123456");
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/"+path);
mClient.startStream();
} else {
// Stops the stream and disconnects from the RTSP server
mClient.stopStream();
}
}
private void logError(final String msg) {
final String error = (msg == null) ? "Error unknown" : msg;
// Displays a popup to report the eror to the user
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onBitrateUpdate(long bitrate) {
mTextBitrate.setText(""+bitrate/1000+" kbps");
}
#Override
public void onPreviewStarted() {
if (mSession.getCamera() == CameraInfo.CAMERA_FACING_BACK) {
mButtonFlash.setEnabled(true);
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
}
else {
mButtonFlash.setEnabled(true);
}
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video_active);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionStopped() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
mProgressBar.setVisibility(View.GONE);
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
mButtonFlash.setTag("off");
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
logError("The following settings are not supported on this phone: "+
quality.toString()+" "+
"("+e.getMessage()+")");
e.printStackTrace();
return;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
logError(e.getMessage());
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception e) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
mProgressBar.setVisibility(View.GONE);
enableUI();
logError(e.getMessage());
e.printStackTrace();
break;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//tried adding the setPreiviewOrientation(90) here also but still nothing changed.
mSession.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mClient.stopStream();
}
}
I have tried to change setPreviewOrientation also but still no changes check the codes i have commented whatever i tried please help me. click here to see the API that i have used
Add this method and call it where camera is open
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Parameters params = c.getParameters();
params.setRotation(rotation);
}
Add these in surfaceChanged method for image clarity and other.
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
for(int i=0;i<sizes.size();i++)
{
if(sizes.get(i).width > size.width)
size = sizes.get(i);
}
parameters.setPictureSize(size.width, size.height);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
parameters.setExposureCompensation(0);
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setJpegQuality(100);
try{
camera.setParameters(parameters);
camera.startPreview();
}catch (Exception e){
}
I am creating a coffee ordering app for school. My intent for the code below is to increment or decrement the coffee integer based on whether the subtractCoffeeButton or addCoffeeButton is clicked. coffeeTV is used to show the user the number of coffee's queued to be ordered. subtotal and subtotalTV are used to hold the price and display it to the user.
As it is, the subtractCoffee and addCoffee buttons work to increment coffee and coffeeTV from 0 to 1 and vise-versa, subtotal and subtotalTV also work for displaying 0.00 and 2.5, but it won't increment any further than that. Further button clicks result in nothing happening when it is expected to increment coffee to 2,3,4,etc. and subtotal to 5.00,7.50,10.00,etc.
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffeeTracker = Integer.parseInt(coffeeString);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffeeTracker == 0) {
break;
} else if (coffeeTracker == 1) {
coffee = 0;
coffeeTracker = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTracker+=1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
These variables have to be outside the onClick method.
Everytime you call onClick they get initiated again with 0.
because
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
are in the local scope of your method. Declare as member variable and their value will persist as long as the current Activity is not destroyed
The problem is that you have
double subtotal = 0.00;
int coffee = 0;
at the beginning of your onClick() function. Thus, every time you click a button, you reset the number to 0 and then increment it to 1.
Besides, I'd recommend you to define separate OnClickListener instead of a global one. Something like:
public class MainActivity extends AppCompatActivity {
AppWidgetManager appWidgetManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
InputMethodManager inputMethodManager;
EditText mainEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager.TaskDescription taskDescription =
new ActivityManager.TaskDescription(null, null, getResources().getColor(R.color.primaryDark));
setTaskDescription(taskDescription);
getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
}
appWidgetManager = AppWidgetManager.getInstance(this);
inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
String savedText = preferences.getString("mainText", "");
mainEditText = (EditText) findViewById(R.id.mainEditText);
mainEditText.setMovementMethod(new ScrollAndSelectMovingMethod());
mainEditText.getText().append(savedText);
Selection.setSelection(mainEditText.getText(), savedText.length());
mainEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputMethodManager.showSoftInput(mainEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
mainEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
onEditTextTextChanged(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
#Override
public void onBackPressed() {
finish();
}
private void onEditTextTextChanged(String text) {
saveText(text);
updateWidget();
}
private void saveText(String text) {
editor.putString("mainText", text);
editor.commit();
}
private void updateWidget() {
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(this, Widget.class));
for (int id : ids)
Widget.updateAppWidget(appWidgetManager, id);
}
}
As already said subtotal, coffe and coffePrice need to be outside of the onClick function. Also coffeTracker should always be the same as coffe as far as I can see, so you dont need the variable
This should be your code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
} else if (coffee == 1) {
coffee = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
Either you go with the other answers approach (field variables) or you read and parse the amounts on each onClick(). In code it would look something like:
static final double COFFEE_PRICE = 2.50;
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffee = Integer.parseInt(coffeeString);
TextView subtotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
String subtotalString = subtotalTV.getText().toString();
double subtotal = Double.parseDouble(subtotalString);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
}
coffee--;
subtotal -= COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
case R.id.addCoffeeButton:
coffee++;
subtotal += COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
}
}
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
I'm designing a simple app to count the rows and stitches in crocheting/knitting, but I'm having issues. The actual counting itself is just a modified calculator: display a text field that holds the current number of stitches, and buttons which allow you to add or subtract 1, 5 or 10 to the count. Problem is, punching the buttons in the emulator doesn't work -- the thing compiles without issues and builds without issues, so I'm thinking it's something small I've (not) done.
My Main file:
public class mainCount extends Activity {
private EditText Scr; //Textbox screen
private int NumberBF; //saves screen before pressing button operations
private String Operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.stitchCount);
int idList[] = {R.id.stitchMin1, R.id.stitchMin5, R.id.stitchMin10, R.id.stitchPlus1, R.id.stitchPlus5, R.id.stitchPlus10, R.id.clearButton};
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#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_count, menu);
return true;
}
public void mMath(String str){
NumberBF = Integer.parseInt(Scr.getText().toString());
Operation = str;
Scr.setText("0");
}
private void getKeyboard(String str){
String ScrCurrent = Scr.getText().toString();
if(ScrCurrent.equals("0"))
ScrCurrent = "";
ScrCurrent += str;
Scr.setText(ScrCurrent);
}
public void mResult(String str){
int NumAf = Integer.parseInt(Scr.getText().toString());
int result = 0;
if(str.equals("+1")){
result = NumAf + 1;
}
if(str.equals("+5")){
result = NumAf + 5;
}
if(str.equals("+10")){
result = NumAf + 10;
}
if(str.equals("-1")){
result = NumAf - 1;
}
if(str.equals("-5")){
result = NumAf - 5;
}
if(str.equals("-10")){
result = NumAf - 10;
}
Scr.setText(String.valueOf(result));
}
// ButtonListener class
private class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton: //Clears stitches for this row
Scr.setText("0");
NumberBF = 0;
Operation = "";
break;
case R.id.stitchPlus1:
Operation = "+1";
mResult(Operation);
break;
case R.id.stitchPlus5:
Operation = "+5";
mResult(Operation);
break;
case R.id.stitchPlus10:
Operation = "+10";
mResult(Operation);
break;
case R.id.stitchMin1:
Operation = "-1";
mResult(Operation);
break;
case R.id.stitchMin5:
Operation = "-5";
mResult(Operation);
break;
case R.id.stitchMin10:
Operation = "-10";
mResult(Operation);
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
}
You're not initializing your btnClick ButtonClickListener. Try changing your code to the following:
btnClick = new ButtonClickListener();
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}