I'm having trouble on displaying an output on my interface.
My program should be able to display respective outputs upon inputting some parameters. If no parameters were entered, it shall display "No results" which is what I have implemented.
However, even with parameters entered . It still displays "No results" instead of the answer according to formula given.
My code is as follow:
public class FreeSpaceActivity extends Fragment implements OnClickListener {
DecimalFormat disp_W = new DecimalFormat("0.000E0");
DecimalFormat disp_dBm = new DecimalFormat("0.000");
EditText tPowerEdit = null;
EditText tGainEdit = null;
EditText rGainEdit = null;
EditText freqEdit = null;
EditText distanceEdit = null;
EditText lightEdit = null;
Button calButton = null;
Button graphButton = null;
Button clearButton = null;
Button plotButton = null;
EditText radEdit = null;//testing
private ScrollView llLayout;
private FragmentActivity faActivity;
//private Switch switch1;
// Changes here
private double mResult = 0;
private Switch mSelectUnit;
private TextView mTextFreeSpaces;
private boolean mIsCalculated;// flag to show the result only when you click on calculate button
private boolean flag;
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(null);
faActivity = (FragmentActivity) this.getActivity();
llLayout = (ScrollView) inflater.inflate(R.layout.activity_free_space, container, false);
tPowerEdit = (EditText)llLayout.findViewById(R.id.editText1);
tGainEdit = (EditText)llLayout.findViewById(R.id.editText2);
rGainEdit = (EditText)llLayout.findViewById(R.id.editText3);
freqEdit = (EditText)llLayout.findViewById(R.id.editText4);
distanceEdit = (EditText)llLayout.findViewById(R.id.editText7);
lightEdit = (EditText)llLayout.findViewById(R.id.editText8);
calButton = (Button)llLayout.findViewById(R.id.button1);
calButton.setOnClickListener(this);
graphButton = (Button)llLayout.findViewById(R.id.button2);
graphButton.setOnClickListener(this);
clearButton = (Button)llLayout.findViewById(R.id.button3);
clearButton.setOnClickListener(this);
plotButton =(Button)llLayout.findViewById(R.id.plot_button);
plotButton.setOnClickListener(this);
radEdit = (EditText)llLayout.findViewById(R.id.editText28);//testing
// Changes here
mTextFreeSpaces = (TextView) llLayout.findViewById(R.id.textFreeSpaces);
mSelectUnit =(Switch)llLayout.findViewById(R.id.switch1);
mSelectUnit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateFreeSpacesText(isChecked);
}
});
return llLayout;
}
/*private ActionBar getSupportActionBar() {
return null;
}*/
private void updateFreeSpacesText(boolean isSwitcherChecked) {
if(mIsCalculated && flag==true){
if(isSwitcherChecked){
double dBm=10 * Math.log10(mResult* 1000);
mTextFreeSpaces.setText(disp_dBm.format(dBm));//display dbm
Toast.makeText(getActivity().getApplicationContext(),"Unit Chosen is dBm", Toast.LENGTH_LONG).show();
} else {
double W=mResult;
mTextFreeSpaces.setText(disp_W.format(W));//display W
Toast.makeText(getActivity().getApplicationContext(),"Unit Chosen is W", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String tPowerStr = tPowerEdit.getText().toString();
String tGainStr = tGainEdit.getText().toString();
String rGainStr = rGainEdit.getText().toString();
String freqStr = freqEdit.getText().toString();
String distanceStr = distanceEdit.getText().toString();
String lightStr = lightEdit.getText().toString();
double tPower = Double.parseDouble(!tPowerStr.isEmpty() ? tPowerStr : "0");
double tGain = Double.parseDouble(!tGainStr.isEmpty() ? tGainStr : "0");
double rGain = Double.parseDouble(!rGainStr.isEmpty() ? rGainStr : "0");
double freq = Double.parseDouble(!freqStr.isEmpty() ? freqStr : "0");
double distance = Double.parseDouble(!distanceStr.isEmpty() ? distanceStr : "1");
double light = Double.parseDouble(!lightStr.isEmpty() ? lightStr : "1");
String radStr = radEdit.getText().toString();//testing
double radius = Double.parseDouble(!radStr.isEmpty() ? radStr : "0");//testing
if (v == calButton) {
if(mResult!=0) {
double lamda = 300000000 / freq;
mResult = tPower * tGain * rGain * Math.pow(lamda / (4 * Math.PI * distance), 2) / light / 100;
mIsCalculated = true;
flag = true;
updateFreeSpacesText(mSelectUnit.isChecked());
}
else
mTextFreeSpaces.setText("No results");
}
else if (v == graphButton) {
Intent intent = new Intent(getActivity(), GraphActivity.class);
intent.putExtra("model", "freeSpace");
intent.putExtra("tp", tPower);
intent.putExtra("tg", tGain);
intent.putExtra("rg", rGain);
intent.putExtra("f", freq);
intent.putExtra("l", light);
this.startActivity(intent);
} else if (v == clearButton) {
flag=false;
double lamda = 300000000 / freq;
((EditText) llLayout.findViewById(R.id.editText1)).setText(null);
((EditText) llLayout.findViewById(R.id.editText2)).setText(null);
((EditText) llLayout.findViewById(R.id.editText3)).setText(null);
((EditText) llLayout.findViewById(R.id.editText4)).setText(null);
((EditText) llLayout.findViewById(R.id.editText7)).setText(null);
((EditText) llLayout.findViewById(R.id.editText8)).setText(null);
((EditText) llLayout.findViewById(R.id.editText28)).setText(null);
((TextView) llLayout.findViewById(R.id.textFreeSpaces)).setText(null);
//((TextView) llLayout.findViewById(R.id.textFreeSpacePrd)).setText("");
//mIsCalculated = true;
//updateFreeSpacesText(mSelectUnit.isChecked());
//mResult=tPower * tGain * rGain * Math.pow(lamda / (4 * Math.PI * distance), 2) / light / 100;
//mTextFreeSpaces.setText("");
} else if (v == plotButton) {
//double radius = Double.parseDouble(radius.getText().toString());
Intent intent = new Intent(getActivity(), MapActivity.class);
Bundle b = new Bundle();
//b.putDouble("radius", result);
intent.putExtras(b);
this.startActivity(intent);
}
}
}
My interface:
I think Stultuske is right but my Reputation is to low to comment.
I would prefer that you change the statement of the IF-Clause
if (v == calButton) {
if(mResult!=0) {
.
.
.
}
else
mTextFreeSpaces.setText("No results");
otherway you're running in the else-branch everytime because your variable mResult is still 0 and hasn't changed.
Maybe you can retreive if the Edittexts are not empty like
if(tPowerStr.matches("") && The other Edittexts) {
.
.
.
}
else
mTextFreeSpaces.setText("No results");
EDIT:
By the way I'm interested in your App because I'm a directional radio and satellite communication engineer.
Related
This is my view activity and in which I want to extract data from another table and save operated data to another table. The problem is the data is adding again and again, and in the view activity, the same data is repeating and filling up the whole space.
public class LastActivity extends AppCompatActivity {
TextView txt;
Button btn;
static MyDB myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
myDB = new MyDB(this);
getSupportActionBar().setTitle("Final Data");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final LinearLayout lm = (LinearLayout) findViewById(R.id.lastactivity);
btn = (Button) findViewById(R.id.subfielddata);
txt = (TextView) findViewById(R.id.textView7);
Bundle bundle = getIntent().getExtras();
String date2 = bundle.getString("date1");
txt.setText(date2);
//create the layout parameters
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = Secondlast_Activity.myDB.getAllTime();
c.moveToFirst();
if (c == null) {
Toast.makeText(getApplicationContext(), "Error!! Cursor is empty", Toast.LENGTH_SHORT).show();
} else {
//create all variants to fetch data from database
while (c.moveToNext()) {
String ename = c.getString(0);
int h1 = c.getInt(1);
int h2 = c.getInt(5);
int m1 = c.getInt(2);
int m2 = c.getInt(6);
int ad = c.getInt(7);
int wages = c.getInt(3);
int a, b, d;
int min = 0, res, hr;
//oode for getting hours from edit text
hr = h1 - h2;
//code for converting values to edit text value to minutes
if (m1 > m2) {
a = 60 - m1;
m2 = a + m2;
min = m2;
hr--;
} else {
if (m1 < m2) {
b = m2 - m1;
min = b;
}
}
hr = hr * (-1);
wages = wages * hr;
//oode for getting hours from edit text
hr = h1 - h2;
//code for converting values to edit text value to minutes
if (m1 > m2) {
a = 60 - m1;
m2 = a + m2;
min = m2;
hr--;
} else {
if (m1 < m2) {
b = m2 - m1;
min = b;
}
}
hr = hr * (-1);
wages = wages * hr;
boolean result = Secondlast_Activity.myDB.insertData(ename,hr, wages);
if (result) {
Toast.makeText(LastActivity.this, hr + " Insertion Complete", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LastActivity.this, "Error!!", Toast.LENGTH_LONG).show();
}
}
}
}
});
//creating cursor for database to let data in count
Cursor c = LastActivity.myDB.getLastData();
c.moveToFirst();
if (c == null) {
Toast.makeText(getApplicationContext(), "Cursor d is empty!!", Toast.LENGTH_SHORT).show();
} else {
//create all variants to fetch data from database
while (c.moveToNext()) {
final String emname = c.getString(0);
final int totalwork = c.getInt(2);
final int Advance = c.getInt(3);
final int totalearn = c.getInt(4);
//create linear layout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
//create textView to show data
TextView Name = new TextView(this);
Name.setText(emname + "");
Name.setWidth(250);
ll.addView(Name);
TextView work = new TextView(this);
work.setText(totalwork + "");
work.setWidth(290);
ll.addView(work);
TextView Ad = new TextView(this);
Ad.setText(Advance + "");
Ad.setWidth(290);
ll.addView(Ad);
TextView earn = new TextView(this);
earn.setText(totalearn + "");
earn.setWidth(250);
ll.addView(earn);
Name.setLayoutParams(params);
lm.addView(ll);
}
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
}
I am making an app which consists of an activity and a service. By pressing a button the service is started, it collects data in the background from a sensor and classifies it and outputs a string. I want to display the string in a textView. Right now I can see in the log that the variable is updated 2 times every second, but when I try and update the textView from the service class nothing is happening unless I press the button, whenever I press the button, the string is displayed in the textView.
What is the easiest solution here? I tried to make the textView static and it still can't update it. Can you make it so that the view is updated automatically every second? Can I add a listener somehow? Since I am not very experienced I would like an easy solution that does not have to be a "good" one.
Here is my code
Activity:
public class CollectorActivity extends Activity {
private enum State {
IDLE, COLLECTING, TRAINING, CLASSIFYING
};
private final String[] mLabels = { Globals.CLASS_LABEL_STANDING,
Globals.CLASS_LABEL_WALKING, Globals.CLASS_LABEL_RUNNING,
Globals.CLASS_LABEL_OTHER };
private RadioGroup radioGroup;
private final RadioButton[] radioBtns = new RadioButton[4];
private Intent mServiceIntent;
private File mFeatureFile;
public static TextView mCurrentLabel;
private State mState;
private Button btnDelete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupLabels);
radioBtns[0] = (RadioButton) findViewById(R.id.radioStanding);
radioBtns[1] = (RadioButton) findViewById(R.id.radioWalking);
radioBtns[2] = (RadioButton) findViewById(R.id.radioRunning);
radioBtns[3] = (RadioButton) findViewById(R.id.radioOther);
btnDelete = (Button) findViewById(R.id.btnDeleteData);
mCurrentLabel = (TextView) findViewById(R.id.textView);
mState = State.IDLE;
mFeatureFile = new File(getExternalFilesDir(null),
Globals.FEATURE_FILE_NAME);
mServiceIntent = new Intent(this, SensorsService.class);
}
public void onCollectClicked(View view) {
if (mState == State.IDLE) {
mState = State.COLLECTING;
((Button) view).setText(R.string.ui_collector_button_stop_title);
btnDelete.setEnabled(false);
radioBtns[0].setEnabled(false);
radioBtns[1].setEnabled(false);
radioBtns[2].setEnabled(false);
radioBtns[3].setEnabled(false);
int acvitivtyId = radioGroup.indexOfChild(findViewById(radioGroup
.getCheckedRadioButtonId()));
String label = mLabels[acvitivtyId];
Bundle extras = new Bundle();
extras.putString(Globals.CLASS_LABEL_KEY, label);
mServiceIntent.putExtras(extras);
startService(mServiceIntent);
} else if (mState == State.COLLECTING) {
mState = State.IDLE;
((Button) view).setText(R.string.ui_collector_button_start_title);
btnDelete.setEnabled(true);
radioBtns[0].setEnabled(true);
radioBtns[1].setEnabled(true);
radioBtns[2].setEnabled(true);
radioBtns[3].setEnabled(true);
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
}
}
public void onDeleteDataClicked(View view) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
if (mFeatureFile.exists()) {
mFeatureFile.delete();
}
Toast.makeText(getApplicationContext(),
R.string.ui_collector_toast_file_deleted,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel(Globals.NOTIFICATION_ID);
}
super.onBackPressed();
}
#Override
public void onDestroy() {
// Stop the service and the notification.
// Need to check whether the mSensorService is null or not.
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
}
finish();
super.onDestroy();
}
And this is the "doInBackground" method in my service class. The line "CollectorActivity.mCurrentLabel.setText(classification);" is the problem. I want this to update the textView continously.
public class OnSensorChangedTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Instance inst = new DenseInstance(mFeatLen);
inst.setDataset(mDataset);
Instance inst2 = new DenseInstance(65);
int blockSize = 0;
FFT fft = new FFT(Globals.ACCELEROMETER_BLOCK_CAPACITY);
double[] accBlock = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double[] re = accBlock;
double[] im = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double max = Double.MIN_VALUE;
while (true) {
try {
// need to check if the AsyncTask is cancelled or not in the while loop
if (isCancelled () == true)
{
return null;
}
// Dumping buffer
accBlock[blockSize++] = mAccBuffer.take().doubleValue();
if (blockSize == Globals.ACCELEROMETER_BLOCK_CAPACITY) {
blockSize = 0;
testList = new ArrayList<Double>();
// time = System.currentTimeMillis();
max = .0;
for (double val : accBlock) {
if (max < val) {
max = val;
}
}
fft.fft(re, im);
for (int i = 0; i < re.length; i++) {
double mag = Math.sqrt(re[i] * re[i] + im[i]
* im[i]);
inst.setValue(i, mag);
testList.add(i,mag);
im[i] = .0; // Clear the field
}
// Append max after frequency component
inst.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
inst2.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
testList.add(max);
classificationIndex = WekaClassifier.classify(testList.toArray());
classification = testLabel.get((int) classificationIndex);
CollectorActivity.mCurrentLabel.setText(classification);
inst.setValue(mClassAttribute, mLabel);
mDataset.add(inst);
Log.i("new instance", mDataset.size() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In doInBackground(Void... arg0) change CollectorActivity.mCurrentLabel.setText(classification); to publishProgress(classification); then change second argument from Void to String: public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> and add onProgressUpdate().
Finally your code should looks like:
public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> {
#Override
protected Void doInBackground(Void... arg0) {
//...
publishProgress(classification);
//...
}
#Override
protected Void onProgressUpdate(String... classification) {
CollectorActivity.mCurrentLabel.setText(classification[0]);
}
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 have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks
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);
}