Im almost getting to the end of my Sound bar project (2 arduinos, relays, digital potentiometers, leds, i2c, bluetooth and ir remote, diy amplifier,...) and I`m stuck.
This is my first time using android studio and things are becoming so hard for me.
I created an app with a few buttons, switch, sliders and dropdown menu that connects to bluetooth module and sends values to my arduino.
Now I need to add a script that would receive values that arduino is sending (got arduino code done), and would eventualy set buttons clickable/unclickable and set slider positions depending on values being received thru bluetooth.
Can somebody please show me the way to read values from bluetooth and store them in integer or something so that buttons could be disabled and enabled with if(integer=x); statements.
I will post my java code (App is almost done, excepet for sliders and this bluetooth receive part) and I will post the code I came with so far...
I`m going nuts on this one.
Thank you for help :)
package com.interface80.soundbarcontrol;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.icu.text.Transliterator;
import android.os.Build;
import android.os.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class Remote extends Activity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "BlueTest5-Controlling";
private int mMaxChars = 50000;//Default//change this to string..........
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private boolean mIsBluetoothConnected = false;
private int mLastSpinnerPosition = 0;
private Button mBtnDisconnect;
private BluetoothDevice mDevice;
final static String on="92";//on
final static String off="79";//off
final static String subon="10";//subon
final static String suboff="15";//suboff
final static String zero="20";//zeroDB
final static String six="25";//sixDB
final static String twelwe="30";//twelweDB
final static String userBoost="40";
final static String softBoost="45";
final static String normalBoost="50";
final static String hardBoost="55";
final static String overloadOn="60";
final static String overloadOff="65";
Switch toggle; //outside oncreate
private ProgressDialog progressDialog;
Button btnon,btnoff, btnsubon, btnsuboff, btnzero, btnsix, btntwelwe;
Switch overloadSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote);
Spinner spinnerPresets = (Spinner) findViewById(R.id.spinnerPresets);
ArrayAdapter<String> adapterPresets = new ArrayAdapter<String>(Remote.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.arrayPresets));
adapterPresets.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPresets.setAdapter(adapterPresets);
spinnerPresets.setOnItemSelectedListener(this);
ActivityHelper.initialize(this);
// mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
btnon = (Button) findViewById(R.id.on);
btnoff = (Button) findViewById(R.id.off);
btnsubon = (Button) findViewById(R.id.subon);
btnsuboff = (Button) findViewById(R.id.suboff);
btnzero = (Button) findViewById(R.id.zero);
btnsix = (Button) findViewById(R.id.six);
btntwelwe = (Button) findViewById(R.id.twelwe);
overloadSwitch = (Switch) findViewById(R.id.overloadSwitch);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
btnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(on.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(off.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsubon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(subon.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsuboff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(suboff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnzero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(zero.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(six.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btntwelwe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(twelwe.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
if (mLastSpinnerPosition == position)
{
return;
}
mLastSpinnerPosition = position;
if (0 == position) {
Toast.makeText(parent.getContext(), "Boost controlled by user.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(true);
btnsix.setEnabled(true);
btntwelwe.setEnabled(true);
try {
mBTSocket.getOutputStream().write(userBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
if (1 == position) {
try {
mBTSocket.getOutputStream().write(softBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (2 == position) {
try {
mBTSocket.getOutputStream().write(normalBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (3 == position) {
try {
mBTSocket.getOutputStream().write(hardBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {//cant inderstand these dotss
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Remote.this, "", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device`
// e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect.Please turn on Sound bar", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to Sound bar");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public void toggle( View View) //outside oncreate
{
if( overloadSwitch.isChecked() ){
try {
mBTSocket.getOutputStream().write(overloadOn.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
else
{
try {
mBTSocket.getOutputStream().write(overloadOff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
}
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
int BTvalue = buffer;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Problem solved.
I spent late night yesterday with no succes. Angry and frustrated I went to bed. Today I found out that none of the codes I was trying didn`t work, because code was already there. Reading and writing to string. Just used the string and done :)
Related
I am using csipsimple code and customised it to show brandname by getting json value from webservice . I am using SharedPreferences to store value .
Once the application is force closed , or device restart SharedPreferences are lost . I am using commit and clear but still the values are null .
BasePrefsWizard is the class responsible for pulling web data and DialerFragment is the other class i am calling the BrandName ( it is SavedBrand/ brand in code)
package com.mydial.wizards;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.EditTextPreference;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mydial.api.SipManager;
import com.mydial.api.SipProfile;
import com.mydial.db.DBProvider;
import com.mydial.models.Filter;
import com.mydial.ui.SipHome;
import com.mydial.ui.dialpad.DialerFragment;
import com.mydial.ui.filters.AccountFilters;
import com.mydial.ui.prefs.GenericPrefs;
import com.mydial.utils.AccountListUtils;
import com.mydial.utils.Log;
import com.mydial.utils.PreferencesProviderWrapper;
import com.mydial.utils.PreferencesWrapper;
import com.mydial.utils.AccountListUtils.AccountStatusDisplay;
import com.mydial.utils.animation.ActivitySwitcher;
import com.mydial.wizards.WizardUtils.WizardInfo;
import com.mydial.wizards.impl.Advanced;
import com.worldfone.R;
#SuppressLint("NewApi") public class BasePrefsWizard extends GenericPrefs {
public static final int SAVE_MENU = Menu.FIRST + 1;
public static final int TRANSFORM_MENU = Menu.FIRST + 2;
public static final int FILTERS_MENU = Menu.FIRST + 3;
public static final int DELETE_MENU = Menu.FIRST + 4;
private PreferencesProviderWrapper prefProviderWrapper;
private static final String THIS_FILE = "Base Prefs wizard";
protected SipProfile account = null;
private Button saveButton,cancel;
private String wizardId = "";
private WizardIface wizard = null;
private BroadcastReceiver mReceiver;
IntentFilter intentFilter;
public static final String myData = "mySharedPreferences";
public static String bal = null;
public static String sip = null;
public static String header = null;
public static String date = null;
public static String savedBal="";
public static String savedSip="";
public static String savedBrand="";
public static String webArray[] =new String[6];
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Get back the concerned account and if any set the current (if not a
// new account is created)
Intent intent = getIntent();
long accountId = 1;
//intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
// TODO : ensure this is not null...
// setWizardId(intent.getStringExtra(SipProfile.FIELD_WIZARD));
setWizardId();
account = SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);
super.onCreate(savedInstanceState);
prefProviderWrapper = new PreferencesProviderWrapper(this);
// Bind buttons to their actions
cancel = (Button) findViewById(R.id.cancel_bt);
//cancel.setEnabled(false);
cancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isOnline();
//saveAndFinish();
}
});
saveButton = (Button) findViewById(R.id.save_bt);
//saveButton.setEnabled(false);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//setResult(RESULT_CANCELED, getIntent());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
wizard.fillLayout(account);
loadValue();
}
public void isOnline()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
try
{
String webAccessNumberLink="http://myweblink.info/test/code.php?user=1234";
new webAccessNumber().execute(webAccessNumberLink);
}
catch(Exception e)
{
// System.out.println("exception in basepreference "+e);
}
}
else
{
// display error
showNetworkAlert();
}
}
void showNetworkAlert()
{
new AlertDialog.Builder(this)
.setTitle("Alert")
.setMessage(
"Please make sure you have Network Enabled")
.setNeutralButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*Intent siphome = new Intent(getApplicationContext(),SipHome.class);
startActivity(siphome);*/
}
}).show();
}
public void saveArray(String[] arrayOfweb)
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences =this.getSharedPreferences(myData,
mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
String f1 = arrayOfweb[0];
String f2 = arrayOfweb[1];
String f3 = arrayOfweb[2];
String f4 = arrayOfweb[3];
for(int i=0;i<arrayOfweb.length;i++)
{
}
//byMe added below to make preferences persistant
editor.clear();
editor.putString("balance",f1);
editor.putString("sipp",f2);
editor.putString("brand",f3);
editor.putString("prfx",f4);
editor.commit();
loadValue();
}
private void loadValue()
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences = this.getSharedPreferences(myData,
mode);
savedBal= mySharedPreferences.getString("balance", "");
savedSip = mySharedPreferences.getString("sipp", "");
savedBrand = mySharedPreferences.getString("barnd", "");
}
private boolean isResumed = false;
#Override
protected void onResume()
{
super.onResume();
isResumed = true;
updateDescriptions();
updateValidation();
//byMe
}
#Override
protected void onPause()
{
super.onPause();
isResumed = false;
//this.unregisterReceiver(this.mReceiver);
}
private boolean setWizardId()
{
try {
wizard=Advanced.class.newInstance();
// wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/*if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}*/
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/* if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
*/ return false;
}
//wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
private boolean setWizardId(String wId) {
if (wizardId == null) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
WizardInfo wizardInfo = WizardUtils.getWizardClass(wId);
if (wizardInfo == null) {
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
try {
wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
#Override
protected void beforeBuildPrefs() {
// Use our custom wizard view
setContentView(R.layout.wizard_prefs_base);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(isResumed) {
updateDescriptions();
updateValidation();
}
}
private void resolveStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, 1);
//status.setTextColor(accountStatusDisplay.statusColor);
//status.setText(accountStatusDisplay.statusLabel);
}
/**
* Update validation state of the current activity.
* It will check if wizard can be saved and if so
* will enable button
*/
public void updateValidation()
{
cancel.setEnabled(wizard.canSave());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// menu.findItem(SAVE_MENU).setVisible(wizard.canSave());
return super.onPrepareOptionsMenu(menu);
}
private static final int CHOOSE_WIZARD = 0;
private static final int MODIFY_FILTERS = CHOOSE_WIZARD + 1;
private static final int FINAL_ACTIVITY_CODE = MODIFY_FILTERS;
private int currentActivityCode = FINAL_ACTIVITY_CODE;
public int getFreeSubActivityCode()
{
currentActivityCode ++;
return currentActivityCode;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Save account and end the activity
*/
public void saveAndFinish()
{
//this.registerReceiver(mReceiver, intentFilter);
saveAccount();
Intent intent = getIntent();
setResult(RESULT_OK, intent);
Intent it = new Intent(this,SipHome.class);
startActivity(it);
finish();
}
void updateStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, account.id);
}
/*
* Save the account with current wizard id
*/
private void saveAccount() {
saveAccount(wizardId);
}
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
/**
* Save the account with given wizard id
* #param wizardId the wizard to use for account entry
*/
private void saveAccount(String wizardId) {
boolean needRestart = false;
PreferencesWrapper prefs = new PreferencesWrapper(getApplicationContext());
account = wizard.buildAccount(account);
account.wizard = wizardId;
if (account.id == SipProfile.INVALID_ID) {
// This account does not exists yet
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());
// After insert, add filters for this wizard
account.id = ContentUris.parseId(uri);
List<Filter> filters = wizard.getDefaultFilters(account);
if (filters != null) {
for (Filter filter : filters) {
// Ensure the correct id if not done by the wizard
filter.account = (int) account.id;
getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());
}
}
// Check if we have to restart
needRestart = wizard.needRestart();
} else {
// TODO : should not be done there but if not we should add an
// option to re-apply default params
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
}
// Mainly if global preferences were changed, we have to restart sip stack
if (needRestart) {
Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
sendBroadcast(intent);
}
}
#Override
protected int getXmlPreferences() {
return wizard.getBasePreferenceResource();
}
#Override
protected void updateDescriptions() {
wizard.updateDescriptions();
}
#Override
protected String getDefaultFieldSummary(String fieldName) {
return wizard.getDefaultFieldSummary(fieldName);
}
private static final String WIZARD_PREF_NAME = "Wizard";
#Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return super.getSharedPreferences(WIZARD_PREF_NAME, mode);
}
private class webAccessNumber extends AsyncTask<String, Void, String>
{
//String balance;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
return getAccessNumber(params[0]);
}
#Override
protected void onPostExecute(String result)
{
if(result!=null)
{
try {
System.out.println("value of webAccessNumber "+result);
byte[] decoded = Base64.decode(result,Base64.DEFAULT);
String decodedStr =new String(decoded, "UTF-8");
//System.out.println(decodedStr);
JSONArray arr = new JSONArray(decodedStr);
//loop through each object
for (int i=0; i<arr.length(); i++)
{
JSONObject jsonObject = arr.getJSONObject(i);
bal = jsonObject.getString("balance");
sip = jsonObject.getString("server");
header = jsonObject.getString("brand");
webArray[1]=bal;
webArray[2]=sip;
webArray[3]=barnd;
saveArray(webArray);
saveAndFinish();
progressDialog.dismiss();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(BasePrefsWizard.this);
progressDialog.setMessage("Loading..............");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
public String getAccessNumber(String b) {
String balance = "";
String currency = "USD";
try {
balance = DownloadText(b).trim();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return balance;
}
String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0,
charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return str;
}
InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}//end of webAccessNumber asynchronus
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
isOnline();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should not clear the SharedPreferences in the onDestroy() method, because when you run your activity or your application again, all the saved values and variables in preferences are deleted, ( like you installed your application for the first time).
PS : here is a tutorial about Using SharedPreferences and Storing Data in Android
You are clearing your preferences in your code,
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
//Preferences cleared
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
This is clearing your preferences.
You are clearing the shared prefereence in onDestroy:
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); // <-- Remove this
saveArray(webArray);
}
You delete it in:
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
Also see this http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
I have my major project on android based home automation system meaning that I have to control home appliances using android bluetooth. I am using HC-05 bluetooth module which receives the string sent to it through my application, sends it to PIC16f877a and the pic in turn depending upon the string received, controls the appliances. Now my problem is that I have been able to pair and connect the devices through my application but my application is not sending the characters which I want to send when I click the button. Note that PIC and the Bluetooth module are working fine. please help me. I am posting my code below hope you guys won't mind.
package com.chainedcat.splashscreen;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityActivity extends Activity{
private BluetoothAdapter BA;
private ArrayList<BluetoothDevice> devices;
private ListView lv;
private TextView text;
private BluetoothSocket btSocket=null;
private ArrayAdapter<String> btArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34EB");
private OutputStream outStream=null;
public void Init(){
BA = BluetoothAdapter.getDefaultAdapter();
text =(TextView) findViewById(R.id.text);
lv = (ListView) findViewById(R.id.listView1);
devices = new ArrayList<BluetoothDevice>();
btArrayAdapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1);
lv.setAdapter(btArrayAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Init();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(selectedDevice.getBondState()== BluetoothDevice.BOND_NONE){
pairDevice(selectedDevice);
}
else if(selectedDevice.getBondState()==BluetoothDevice.BOND_BONDED){
connect(selectedDevice);
}
}
});
}
public void bluetooth(View view){
if(!BA.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on!!", Toast.LENGTH_LONG).show();
btExtra();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth is already on!!", Toast.LENGTH_LONG).show();
btExtra();
}
}
public void btExtra(){
btArrayAdapter.clear();
BA.startDiscovery();
registerReceiver(btReceiver, new tentFilter(BluetoothDevice.ACTION_FOUND));
}
final BroadcastReceiver btReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String status=null;
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
status="paired";
}else{status="not paired";}
btArrayAdapter.add(device.getName()+" : "+status+"\n"+device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode==REQUEST_ENABLE_BT){
if(BA.isEnabled()){
text.setText("Bluetooth Status:Enabled");
}else{
text.setText("Bluetooth Status:Disabled");
}
}
}
private void pairDevice(BluetoothDevice device) {
Method m=null;
try {
m = device.getClass().getMethod("createBond", (Class[]) null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
m.invoke(device, (Object[]) null);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect(device);
}
public void connect(BluetoothDevice device){
Toast.makeText(getApplicationContext(), "connecting....", Toast.LENGTH_LONG).show();
try {
btSocket=device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BA.cancelDiscovery();
try {
Toast.makeText(getApplicationContext(), "entered in run", Toast.LENGTH_LONG).show();
btSocket.connect();
if(btSocket!=null){btSocket.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = s.getBytes();
try {
outStream.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fan(View v){
send("f");
}
#Override
public void onDestroy(){
super.onDestroy();
BA.disable();
unregisterReceiver(btReceiver);
}
}
When I am trying to call a number from listview, the dialer opens but shows me some different. The listview consists of two image button, one button is used to make call.
This is my Custom Adapater Class EmergencyNumCustomAdapaterForCall.java.
package com.example.panicapp;
import java.util.List;
import com.example.panicapp.AppDao.AddEmerNumAuthenticationDao;
import com.example.panicapp.AppModel.AddEmergencyNumber;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ListAdapter;
public class EmergencyNumCustomAdapaterForCall extends ArrayAdapter<AddEmergencyNumber> implements ListAdapter{
private List<AddEmergencyNumber> lsadd;
private LayoutInflater inflator;
private AddEmerNumAuthenticationDao emerdao=null;
public EmergencyNumCustomAdapaterForCall(AddEmergencyNumberForCall addnum, List<AddEmergencyNumber> ls)
{
super(addnum, R.layout.activity_custom_numberlisting, ls);
// TODO Auto-generated constructor stub
this.lsadd=ls;
inflator=addnum.getLayoutInflater();
}
static class ViewHolder
{
protected TextView emernumber;
protected ImageButton imgbtncall;
protected ImageButton imgbtnDelete;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder viewholder=null;
final int temposition=arg0;
if(arg1==null)
{
arg1=inflator.inflate(R.layout.activity_custom_numberlisting, null);
viewholder=new ViewHolder();
viewholder.emernumber=(TextView)arg1.findViewById(R.id.txt_numberlisting);
viewholder.imgbtncall=(ImageButton)arg1.findViewById(R.id.img_numberlisting);
viewholder.imgbtnDelete=(ImageButton)arg1.findViewById(R.id.img_numdelete);
viewholder.imgbtnDelete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
emerdao=new AddEmerNumAuthenticationDao(getContext());
emerdao.deleteCallNum(lsadd.get(temposition).getEmergencyNumber());
Log.i("Authentication", "Number Deleted");
}
});
viewholder.imgbtncall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
emerdao=new AddEmerNumAuthenticationDao(getContext());
emerdao.getEmergencyNumberForCalling(lsadd.get(temposition).getEmergencyNumber());
String number=""+emerdao;
System.out.println(number);
Log.i("Number", "Calling Number");
Intent callintent=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" +emerdao));
getContext().startActivity(callintent);
}
});
arg1.setTag(viewholder);
arg1.setTag(R.id.txt_numberlisting, viewholder.emernumber);
arg1.setTag(R.id.img_numberlisting, viewholder.imgbtncall);
arg1.setTag(R.id.img_numdelete, viewholder.imgbtnDelete);
}
else
{
viewholder=(ViewHolder)arg1.getTag();
}
viewholder.imgbtncall.setTag(arg0);
viewholder.imgbtnDelete.setTag(arg0);
viewholder.emernumber.setText(lsadd.get(arg0).getEmergencyNumber());
return arg1;
}
}
This is my database class
package com.example.panicapp.AppDao;
import java.util.ArrayList;
import java.util.List;
import com.example.panicapp.AppModel.AddEmergencyNumber;
import com.example.panicapp.AppUtill.DbUtill;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class AddEmerNumAuthenticationDao extends SQLiteOpenHelper implements AddEmerNumAuthenticationListener{
private SQLiteDatabase sqlDb=null;
public AddEmerNumAuthenticationDao(Context context) {
super(context, DbUtill.DATABASE_NAME, null, DbUtill.DATABASE_VERSION);
Log.i("AuthenticationDao", "This is AuthenticationDao constructor.....");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
public List<AddEmergencyNumber> getAllEmergencyNumberforcall()
{
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.CALL}, DbUtill.CALL+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setCall(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public List<AddEmergencyNumber> getAllEmergencyNumberforsms() {
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.SMS}, DbUtill.SMS+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setSms(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public List<AddEmergencyNumber> getAllNumberforGps() {
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.GPS}, DbUtill.GPS+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setGps(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public void deleteAllCallNum()
{
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.CALL+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteAllSmsNum()
{
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.SMS+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteAllGpsNum() {
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.GPS+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
public void deleteCallNum(String i)
{
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(i)});
Log.i("DELETECALLNUMBER", "DeletionNumber");
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
public void deleteSmsNum(String id)
{
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(id)});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteGpsNum(String id) {
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(id)});
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void getEmergencyNumberForCalling(String id) {
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
String query="SELECT "+DbUtill.EMERGENCYNUMBER+" FROM "+DbUtill.TABLE_ADD_EMERGENCY_NUMBER+" WHERE "+DbUtill.CALL+ "=?"+" ";
sqlDb.rawQuery(query, null);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
}
I am successfully passing string from my android to computer(through WiFi) using two simple button.but my question is i want to use single radio button (as toggle) instead of two simple button .here is my code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private Button button1;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV ON" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV OFF" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}
Lets Consider,
RadioButtonGroup ID : ControlTVRadioButtonGroup
Radio Buttons in this group are : TV_on_rb and TV_off_rb
code:
ControlTVRadioButtonGroup= (RadioGroup) view.findViewById(R.id.ControlTVRadioButtonGroup);
ControlTVRadioButtonGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.TV_on_rb)
{
//code you have written in onclick of button (i.e for tv_on)
}
else if(checkedId == R.id.TV_off_rb)
{
//code you have written in onclick of button1 (i.e for tv_off)
}
}
});
I think you want to look into using a CheckBox instead of a radio button group. It's a simple two-state button (checked or unchecked). From the documentation:
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
if (checkBox.isChecked()) {
checkBox.setChecked(false);
}
Hi I am creating a client-server application with an android device as the client. In my application, my client (android device) sends a request and the server has a response to the request.
I noticed that any method that causes the main thread to wait has to be done on a different thread. I am trying to do that but in my case use a ThreadExecutor. I implemented a helper Runnable class with I pass my ObjectInputStream to but for some reason, its always null. I have checked on a number of questions here but it seems most of them are about how to pass from one activity to another. However I would like to pass from my activity to my helper class and I am not sure of what to do.
Here is my code, I hope it makes more sense.
package com.dozie.service;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
private Button registerButton;
private Button cancelButton;
private TextView errorText;
private EditText firstnameField, lastnameField, passwordField, cPasswordField, usernameField;
private String fname, lname, pword, cPword, uname;
private Socket socket;
private TextWatcher fnameWatcher, lnameWatcher, pwordWatcher, cPwordWatcher, unameWatcher;
protected ObjectOutputStream os;
protected ObjectInputStream is;
private ExecutorService threadPool;
private RegisterWorker worker;
public static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
public static final String USERNAME_PATTERN = "^[A-z0-9_-]{5,20}$";
public static final String TAG = RegisterActivity.class.getName();
public static final int SAMEFIRSTUSER = 100; //same first name and username,
public static final int SAMELASTUSER = 200; //same last name and username
public static final int SAMEPASSFIRST = 300; //same password and firstname
public static final int SAMEPASSLAST = 400; //same password and lastname
public static final int SAMEPASSUSER = 500; //same password and username
public static final int USERNOTMATCH = 600; //username does not match
public static final int PASSNOTMATCH = 700; //password does not match
public static final int CPASS_DIFF = 800; //password and confirm password are different
public static final int GOODINPUT = 1; //every input is good
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerButton = (Button) findViewById(R.id.register_id);
cancelButton = (Button) findViewById(R.id.cancel_id);
firstnameField = (EditText) findViewById(R.id.firstname_id);
lastnameField = (EditText) findViewById(R.id.lastname_id);
passwordField = (EditText) findViewById(R.id.rpassword_id);
cPasswordField = (EditText) findViewById(R.id.rcpassword_id);
usernameField = (EditText) findViewById(R.id.rusername_id);
errorText = (TextView) findViewById(R.id.errorText_id);
fname="";lname="";pword="";cPword="";uname="";
//initialize TextWatchers
initializeWatchers();
// add TextWatchers
firstnameField.addTextChangedListener(fnameWatcher);
lastnameField.addTextChangedListener(lnameWatcher);
passwordField.addTextChangedListener(pwordWatcher);
cPasswordField.addTextChangedListener(cPwordWatcher);
usernameField.addTextChangedListener(unameWatcher);
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
firstnameField.setText("");
lastnameField.setText("");
passwordField.setText("");
cPasswordField.setText("");
usernameField.setText("");
setResult(RESULT_CANCELED);
finish();
}
});
}
#Override
public void onStart()
{
super.onStart();
Log.d(TAG, "onStart()");
Intent intent = getIntent();
final String address = intent.getStringExtra("ipAddress");
final int port = intent.getIntExtra("port", 6060);
threadPool = Executors.newFixedThreadPool(2);
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Log.i(TAG, "Trying to Connect to "+ address + " on " + port);
socket = new Socket(address, port);
Log.i(TAG, "Connection established!");
os = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
is = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
Log.i(TAG, "Client connected to server.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnknownHostException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
}
}).start();
// threadPool.execute(worker = new RegisterWorker(is));;
}
#Override
public void onPause()
{
super.onPause();
Log.d(TAG, "onPause()");
threadPool.shutdown();
Message out = new Message("disconnect");
out.setRequest(Event.Request.DISCONNECT);
try {
os.writeObject(out);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
finally
{
try {
is.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i(TAG, "socket closed");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_register, menu);
return true;
}
public int validateInput(String [] input)
{
String firstname = input[0];
String lastname = input[1];
String password = input[2];
String cpassword = input[3];
String username = input[4];
Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
Matcher matcher = pattern.matcher(password);
Pattern p = Pattern.compile(USERNAME_PATTERN);
Matcher m = p.matcher(username);
if(firstname.equals(username))
return RegisterActivity.SAMEFIRSTUSER;
if(lastname.equals(username))
return RegisterActivity.SAMELASTUSER;
if(firstname.equals(password))
return RegisterActivity.SAMEPASSFIRST;
if(lastname.equals(password))
return RegisterActivity.SAMEPASSLAST;
if(password.equals(username))
return RegisterActivity.SAMEPASSUSER;
if(!password.equals(cpassword))
return RegisterActivity.CPASS_DIFF;
if(!matcher.matches())
return RegisterActivity.PASSNOTMATCH;
if(!m.matches())
return RegisterActivity.USERNOTMATCH;
return RegisterActivity.GOODINPUT;
}
public void registerUser(View v)
{
String [] input = getUserInformation();
int result = validateInput(input);
switch(result)
{
case RegisterActivity.GOODINPUT:
Intent info = new Intent();
info.putExtra("username", input[4]);
registerUser(input);
if(worker.getServerResponse() != null)
{
if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
threadPool.shutdown();
setResult(RESULT_OK, info);
finish();
Log.i(TAG, "registerUser(): data input successful!");
}
else if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
threadPool.execute(worker);
Log.i(TAG, "registerUser(): data input unsuccessful!");
}
}
break;
case RegisterActivity.SAMEFIRSTUSER:
errorText.setText("username should not be the same as firstname");
Log.i(TAG, "registerUser(): username same as firstname");break;
case RegisterActivity.SAMELASTUSER:
errorText.setText("username should not be the same as lastname");
Log.i(TAG, "registerUser(): username same as lastname");break;
case RegisterActivity.SAMEPASSFIRST:
errorText.setText("password should not be the same as firstname");
Log.i(TAG, "registerUser(): password same as firstname");break;
case RegisterActivity.SAMEPASSLAST:
errorText.setText("password should not be the same as lastname");
Log.i(TAG, "registerUser(): password same as lastname");break;
case RegisterActivity.SAMEPASSUSER:
errorText.setText("password should not be the same as username");
Log.i(TAG, "registerUser(): password same as username");break;
case RegisterActivity.CPASS_DIFF:
errorText.setText("password and confirm password are not the same");
Log.i(TAG, "registerUser(): password and confirm password not the same");break;
case RegisterActivity.PASSNOTMATCH:
errorText.setText("password format wrong. Password should contain 6-20 characters\n" +
"characters containing at least 1 digit, 1 lower case alphabet and 1 upper case character");
Log.i(TAG, "registerUser(): password format not correct");break;
case RegisterActivity.USERNOTMATCH:
errorText.setText("username format wrong. username should contain 5-20 characters " +
"and should have to special characters");
Log.i(TAG, "registerUser(): username format not correct");break;
default:
Log.i(TAG, "registerUser(): Code not handled");break;
}
}
public String [] getUserInformation()
{
String firstname = firstnameField.getText().toString();
String lastname = lastnameField.getText().toString();
String password = passwordField.getText().toString();
String cpassword = cPasswordField.getText().toString();
String username = usernameField.getText().toString();
String [] input = {firstname, lastname, password, cpassword, username};
return input;
}
public void initializeWatchers()
{
fnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
fname = firstnameField.getText().toString();
fname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
lnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
lname = lastnameField.getText().toString();
lname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
pwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
pword = passwordField.getText().toString();
pword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
cPwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
cPword = cPasswordField.getText().toString();
cPword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
unameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
uname = usernameField.getText().toString();
uname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
}
public void updateButton()
{
boolean enabled = fname.length()>0 && lname.length()>0 && pword.length()>0
&& cPword.length()>0 && uname.length() >0;
registerButton.setEnabled(enabled);
}
public void registerUser(String [] input)
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Register");
doc.appendChild(rootElement);
Element user = doc.createElement("user");
rootElement.appendChild(user);
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode(input[0]));
user.appendChild(firstname);
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode(input[1]));
user.appendChild(lastname);
Element password = doc.createElement("password");
password.appendChild(doc.createTextNode(input[2]));
user.appendChild(password);
Element username = doc.createElement("username");
username.appendChild(doc.createTextNode(input[4]));
user.appendChild(username);
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String content = writer.toString();
Message out = new Message(content);
out.setRequest(Event.Request.REGISTER);
os.writeObject(out);
Log.d(TAG, "registerUser(): Register message sent");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): ParserConfigurationException error", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): TransformerException error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): IOException error", e);
}
}
}
<p>And for my runnable class</p>
package com.dozie.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import android.util.Log;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
public class RegisterWorker implements Runnable{
private ObjectInputStream is;
private Message in;
public static final String TAG = RegisterWorker.class.getName();
public RegisterWorker(ObjectInputStream is)
{
this.is = is;
if(this.is == null)
System.out.println("null");
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((in = (Message) is.readObject())!=null)
{
if(in.getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
}
else if(in.getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
//give reason for rejection
}
}
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Message getServerResponse()
{
return in;
}
}
I think the code you're writing is way more complicated than it needs to be. If you want to pass variables to a Thread, which is what I think you're trying to do, just do this:
public Worker extends AsyncTask<Arguments, Void, Void> {
// method names may be slightly incorrect, writing this from memory
public void runInBackground(Arguments...args) {
// do what you want to do in the background
}
}
Then start your thread:
Arguments args = new Arguments(arg1, arg2); // whatever you want to pass along
new Worker().execute(args);
Where Arguments can be any class, using this as an example.
Hope this helps.
Simple way is create a static variable and assign the value to it.
Other Solution is create an object with list of values to be carried between the runnable and activity, and pass this object when creating instance
in your case it may look like
MyObject myObject = null;
public RegisterWorker(ObjectInputStream is, MyObject myObject)
{
this.is = is;
this.myObject=myObject;
if(this.is == null)
System.out.println("null");
}
and when processing is finished you add a method where by you can return the object
so your activity class can call that method and use it for further processing.
public MyObject getMyObject(){
retunr myObject
}
But one more way you can try is, Use AsyncTask. Where by you can mention what to return while creating AsyncTask.