How connect to sql server express with android - android

Firstly I wan't you to know that I search really hard for my problem but I found nothing ...
I can't connect to sql server express instance with android application however I try to connect with jdbc:jtds:sqlserver the driver of sourceforge.
I don't forget to add this line in the manifest file :
<uses-permission android:name="android.permission.INTERNET" />
And the error message is Unable to get information from sql server :HostName
Here my source code perhaps there is something wrong :
public class MainActivitySF extends Activity {
private Connection connection;
private Statement statement;
private ResultSet resultat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void OnClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
EditText ehost = (EditText) findViewById(R.id.ehost);
EditText eport = (EditText) findViewById(R.id.eport);
EditText ebase = (EditText) findViewById(R.id.ebase);
EditText euser = (EditText) findViewById(R.id.euser);
EditText epasswd = (EditText) findViewById(R.id.epasswd);
switch (v.getId()) {
case R.id.Connection:
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e){
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
} catch (ClassNotFoundException e1) {
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
} catch(IllegalAccessException e2){
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
}
try {
String connString = "jdbc:jtds:sqlserver://"+ehost.getText().toString()+"" +
":"+eport.getText().toString()+"/"+ebase.getText().toString()+"" +
";encrypt=false;user="+euser.getText().toString()+";" +
"password="+epasswd.getText().toString()+";instance=SQLEXPRESS;";
String username = euser.getText().toString();
String password = epasswd.getText().toString();
connection = DriverManager.getConnection(connString,username,password);
} catch (SQLException e) {
connection = null;
Toast.makeText(this, "connection failled",
Toast.LENGTH_LONG).show();
tv.setText(e.getLocalizedMessage());
return;
}
tv.setText("connection OK !!");
break;
case R.id.statement:
try {
statement = connection.createStatement();
} catch (SQLException e) {
statement=null;
Toast.makeText(this, "statement failled",
Toast.LENGTH_LONG).show();
return;
}
tv.setText("statement OK !!");
break;
case R.id.req:
try {
resultat = statement.executeQuery(
"SELECT * FROM produits");
tv.setText(resultat.getString("LIB_PRODUIT")+ " OK !!");
} catch (SQLException e) {
Toast.makeText(this, "req failled",
Toast.LENGTH_LONG).show();
return;
}
break;
default:
break;
}
}
}

Related

set fetched data from database to a textview after calling intent

I've created a Textview with a null value and button in my my Mainactivity and fetched some data from sql database server using AsyncTask method on button click and stored in to my textview. Then I called an intent to another activity activity2 to show something and I returned to my Mainactivity using intent.But I can't view the previously set data in textview. It shows null value.I want to set it previously fetched data.how can I set that?
public class MainActivity extends Activity {
public ImageView prev, now, next;
String depvisitid;
public TextView display, bottom, ptname, docname;
public String tokenh,tokenext,tokennow;
public String pname,pnamenext,pnamenow;
public boolean status;
public String drname,current;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (ImageView) findViewById(R.id.previmg);
now = (ImageView) findViewById(R.id.token);
next = (ImageView) findViewById(R.id.nextimg);
display = (TextView) findViewById(R.id.textView2);
ptname = (TextView) findViewById(R.id.textView3);
bottom = (TextView) findViewById(R.id.tokennum);
docname = (TextView) findViewById(R.id.textView);
// Connect runner = new Connect();
// runner.execute();
The setOnClickListener method:
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String sleepTime = time.getText().toString();
}
});
now.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
display.setText(tokenh);
ConnectNow nw = new ConnectNow();
nw.execute();
Intent i = new Intent(getApplicationContext(), StatusUpdate.class);
i.putExtra("patientname", pname);
i.putExtra("tokenno", tokenh);
i.putExtra("depvisitid", depvisitid);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connect runner = new Connect();
runner.execute();
}
});
}
The onBackPressed:
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
// finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
class Connect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet reset1 = null;
try {
reset1 = stmt.executeQuery(" select a.TOKENNO,b.FNAME,a.TOKENSTATUS,e.EMPFNAME,a.DEPVISITID from DEPTVISIT a,PATIENT_MASTER b,APP_EMPLOYEE e where a.PID=b.PID and (a.TOKENSTATUS='O' or a.TOKENSTATUS='S' ) and e.EMPID=a.EMPID and a.EMPID=2 and CONVERT(date,a.OPDATE)='2016-05-09' order by TOKENNO desc;");
while (reset1.next()) {
tokenh = reset1.getString("TOKENNO");
pname = reset1.getString("FNAME");
drname = reset1.getString("EMPFNAME");
depvisitid= reset1.getString("DEPVISITID");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return tokenh;
}
protected void onPostExecute(String result) {
bottom.setText(tokenh);
ptname.setText(pname);
docname.setText(drname);
}
}
The connect now class:
class ConnectNow extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "ssssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj****");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open****");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='S' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
System.out.println("status updated to S");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return status;
}
protected void onPostExecute(Boolean result) {
bottom.setText(tokenh);
ptname.setText(pnamenext);
docname.setText(drname);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings=new Intent(getApplicationContext(),Settings.class);
startActivity(settings);
}
return super.onOptionsItemSelected(item);
}
}
SECOND ACTIVITY StatusUdate.java:
public class StatusUpdate extends Activity {
public String tokenstatN, tokenstatY;
Button visited, notvisited;
String pname,tokennum,depvisitid;
TextView patnam,tknum;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statusupdate);
visited = (Button) findViewById(R.id.button);
notvisited = (Button) findViewById(R.id.button2);
patnam= (TextView) findViewById(R.id.textView4);
tknum= (TextView) findViewById(R.id.textView5);
Bundle extras = getIntent().getExtras();
pname = extras.getString("patientname");
tokennum = extras.getString("tokenno");
depvisitid = extras.getString("depvisitid");
patnam.setText(pname);
tknum.setText(tokennum);
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
The NotVisit class:
class NotVisit extends AsyncTask<String, String, Boolean> {
boolean status = false;
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openhhhh");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "openlll");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='N' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.d("status", String.valueOf(status));
return status;
}
}
Whenever you wish to go to previous screen, Always finish the Activity that is on top. Here in your case, You are always creating new instance of MainActivity and this is the reason for getting null when you go back. Try using this in your StatusUpdate.java.
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
StatusUpdate.this.finish();
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
StatusUpdate.this.finish();
}
});
You can store the retrieved text in a static field of your activity class, but it's better save and restore it on activity recreation.So modify your activity like:
#Override
public void onCreate(Bundle b) {
// activity initialization
// textView = ...
if (b != null) {
textView.setText(b.getString("dbtext"));
}
}
and
#Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
b.putString("dbtext", textView.getText());
}

Arduino Android Bluetooth Serial Communication

I have an Arduino Bluetooth shield HC-05. I paired the Bluetooth shield first with Android device and tried to send data to Arduino via Bluetooth shield. Android app sends data to the shield. But Arduino not receiving the command more than (4 to 13) times I think my app not holding the connection properly with the Bluetooth shield, I am not sure about the problem. I tried with the same Arduino code with some other Android application. It was working well. So problem is in my code only. I am using log to monitor the flow of code. The data is sending from the Android device and the Bluetooth is live and still paired. I think Bluetooth shield was not receiving or it was receiving and not passing the data to Arduino. I am troubling for couple of weeks.
Thanks in Advance !!
My code goes here...
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
//
//Bluetooth sender ends
//
//
private final BroadcastReceiver commandAction = new BroadcastReceiver() {
#Override
public void onReceive(Context context2, Intent intent2) {
String com = intent2.getStringExtra("key");
commandAction(com);
Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commandAction("up");
}
});
GCMRegistrar.checkDevice( this );
GCMRegistrar.checkManifest( this );
final String regId = GCMRegistrar.getRegistrationId( this );
if( regId.equals( "" ) ) {
GCMRegistrar.register( this, "501396392354" );
Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
Log.v( TAG2, "Already registered" );
Log.v(TAG2, "Registration id is: " + regId );
}
startService(new Intent(MainActivity.this, LocationService.class));
CheckBt();
Connect();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e("Jon", device.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("in.robot.gcm.commandaction");
registerReceiver(commandAction, intentFilter);
if (mInputStream != null && mOutputStream != null) {
return;
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(commandAction);
closeAccessory();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
stopService(new Intent(MainActivity.this, LocationService.class));
try {
btSocket.close();
} catch (IOException e) {
}
super.onDestroy();
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Log.d(TAG, "accessory opened");
} else {
Log.d(TAG, "accessory open fail");
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void commandAction(String command){
byte[] buffer = new byte[1];
MediaPlayer mp;
Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();
if("up".equals(command)){
buffer[0]=(byte)0;
Log.v(TAG ,"up heay");
writeData("1");
Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
}
else if("down".equals(command)) {
buffer[0]=(byte)1;
Log.v(TAG ,"down heay");
writeData("2");
}
else if("left".equals(command)){
buffer[0]=(byte)2;
writeData("3");
}
else if("right".equals(command)){
buffer[0]=(byte)3;
writeData("4");
}
else if("break".equals(command)){
buffer[0]=(byte)4;
writeData("0");
}
else if("camera left".equals(command)){
buffer[0]=(byte)5;
//writeData("0");
}
else if("camera right".equals(command)){
buffer[0]=(byte)6;
//writeData("0");
}
else if ("jigsaw1".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);
mp.start();
}
else if("jigsaw2".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);
mp.start();
}
else if("horn".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.horn);
mp.start();
}
else if("start".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.start);
mp.start();
}
else if("ghosts".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);
mp.start();
}
else if("flash on".equals(command)){
if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) && !(isLighOn)){
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
isLighOn=true;
Log.v("camera","flash on");
}
else{Log.v("camera","flash not exsisted");}
}
else if("flash off".equals(command)){
if(isLighOn){
cam.stopPreview();
cam.release();
isLighOn=false;
Log.v("camera","flash off");
} }
else if("location on".equals(command)){
startService(new Intent(MainActivity.this, LocationService.class));
}
else if("location off".equals(command)){
stopService(new Intent(MainActivity.this, LocationService.class));
}
else if("speed min".equals(command)){
buffer[0]=(byte)7;
}
else if("speed min".equals(command)){
buffer[0]=(byte)8;
}
else if("speed max".equals(command)){
buffer[0]=(byte)9;
}
else{
Log.v(TAG ,"no command recieved");}
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "write failed", e);
}
}
}
//
//
//
//
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
Toast.LENGTH_SHORT).show();
}
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect() {
Log.d(TAG, address);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "Socket creation failed");
Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
}
//beginListenForData();
}
private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
}
}
}

restoring application background with sharedpreference

I understand that a similar question has been asked but I am seriously stuck on this problem.
When I close the application, it says "Saving Data" which means my on stop method is being called but when I re open the app, it fails to mention that it is "getting data" meaning my onStart method is not being called.
The middle block of code seems to be the most important, I just wanted to include all of it so that if someone were to bump into my situation again, they could see everything.
How do I use the sharedpreferences class in this situation to save the background color and call the onStart method when I reopen the application?
As of now, it always resorts to the default Colour.
Thank you for your time.
EditText ed;
String background_color;
String Color_Value;
String Message;
int datablock =100;
int selectedItem;
int Color_Position;
int change=0;
View root;
View someView;
SharedPreferences prefer;
SharedPreferences.Editor prefer_edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
ActionBar bar = getActionBar();
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
//Hides app title and icon
if (Color_Value!= null){
onStart();
}
else {
}
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//Creates a spinner
ed = (EditText)findViewById(R.id.edit);
final String[] dropdown = getResources().getStringArray(R.array.Colors);
ArrayAdapter <String> adapter = new ArrayAdapter<String>(bar.getThemedContext(),
android.R.layout.simple_spinner_item,android.R.id.text1,dropdown);
//sets up the drop down navigation list in the action bar
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setListNavigationCallbacks(adapter, new OnNavigationListener(){
#Override
public boolean onNavigationItemSelected(int selectedItem, long arg1) {
//Java always starts counting at zero
if (selectedItem == 0){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#005640")));
Color_Position =Color.parseColor("#005640");
//prefer_edit.putInt("background_color", ((Color.parseColor("#005640"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 1){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#045345")));
Color_Position =Color.parseColor("#045345");
//prefer_edit.putInt("background_color", ((Color.parseColor("#045345"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 2){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#384355");
root.setBackgroundColor((Color.parseColor("#384355")));
//prefer_edit.putInt("background_color", ((Color.parseColor("#384355"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 3){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#990088");
root.setBackgroundColor((Color.parseColor("#990088")));
//prefer_edit.putInt("background_color",((Color.parseColor("#990088"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 4){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#026211");
root.setBackgroundColor((Color.parseColor("#026211")));
// prefer_edit.putInt("background_color", (Color.parseColor("#026211")));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
return true;
}
});
}
public void onStart(){
super.onStart();
Log.i("Getting Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value,0);
prefer.getInt(background_color, 0);
}
public void onStop(){
super.onStop();
Log.i("Saving Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value, 0);
SharedPreferences.Editor prefer_edit = prefer.edit();
prefer_edit.putInt(background_color, Color_Position);
prefer_edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_box, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case
R.id.action_settings:
//Pass data between activities here
break;
case
R.id.action_save:
SaveData();
break;
case
R.id.action_error:
LoadData();
break;
case
R.id.action_edit:
ChangeTextColor(change);
change++;
break;
}
return true;
}
public void SaveData(){
Message =ed.getText().toString();
try {
FileOutputStream out = openFileOutput("text.txt", MODE_PRIVATE);
OutputStreamWriter output = new OutputStreamWriter(out);
try{
output.write(Message);
output.flush();
output.close();
Toast.makeText(getBaseContext(), "Save successful", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void LoadData(){
try {
FileInputStream fis = openFileInput("text.txt");
InputStreamReader ins = new InputStreamReader(fis);
//Deserialize the file
char[] Data = new char [datablock];
String final_data ="";
int size;
try {
while((size = ins.read(Data))>0){
String read_data = String.copyValueOf(Data, 0 ,size);
final_data+=read_data;
Data = new char[datablock];
}
Toast.makeText(getBaseContext(), "Message : " + final_data, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Methods galore!
public void ChangeTextColor(int change){
if ((change % 2) == 0) {
// number is even
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Toast.makeText(getApplicationContext(), "Text color changed to red", Toast.LENGTH_LONG).show();
change++;
}
else {
// number is odd
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.black));
Toast.makeText(getApplicationContext(), "Text color changed to black", Toast.LENGTH_LONG).show();
change++;
}
}
}
onStart is called after onCreate, please remove this
if (Color_Value!= null){
onStart();
}
else {
}
and you can retrieve the color fron SharedPreferences directly in onCreate.

how to write 8 bit using outStream.write(msgBuffer);

outStream.write(msgBuffer);
It writes only first bit. how to write 8 bit out of it.If we are sending 00000001 means it writes only 0. But we want to write whole 8 bit how to achieve it.
public class MainActivity extends ActionBarActivity {
private ToggleButton power, simulation, reset, pause, replay, diagnose,
abs, emergency;
private static final String TAG = "bluetooth1";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:12:02:28:75:34";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power = (ToggleButton) findViewById(R.id.toggleButton1);
simulation = (ToggleButton) findViewById(R.id.simulation_tb);
reset = (ToggleButton) findViewById(R.id.reset_bt);
pause = (ToggleButton) findViewById(R.id.pause_bt);
replay = (ToggleButton) findViewById(R.id.replay_bt);
diagnose = (ToggleButton) findViewById(R.id.diagnose_bt);
abs = (ToggleButton) findViewById(R.id.abs_bt);
emergency = (ToggleButton) findViewById(R.id.emergency_bt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
power.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (power.isChecked()) {
String str = "1";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0, binarystr.length(), buffer, 0);
System.out.println("char array:: "
+ Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
sendData(Integer.toBinaryString(b & 255 | 256)
.substring(1));
}
Toast.makeText(getApplicationContext(), "LED ON",
Toast.LENGTH_LONG).show();
} else {
sendData("0");
Toast.makeText(getApplicationContext(), "LED OFF",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.const_closeApp))
.setPositiveButton(getString(R.string.const_yes),
dialogClickListener)
.setNegativeButton(getString(R.string.const_no),
dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(new
// BTStateChangedBroadcastReceiver());
System.exit(0);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
Log.d(TAG, "...This is the value byte: " + msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static byte[] getbyteFromString(char[] binarystr) {
int length = binarystr.length / 8;
if (binarystr.length % 8 > 0)
length++;
int iterationCount = length;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for (int i = binarystr.length - 1; i >= 0;) {
byte byt = 0x0;
for (int j = 0; j < 8; j++) {
if (i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
/*
* try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
* catch (IOException e) { errorExit("Fatal Error",
* "In onResume() and socket create failed: " + e.getMessage() + "."); }
*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
}
It looks like your code is not complete. Anyway, I suggest to use the DataInputStream / DataOutputStream of Android. Just wrap your streams into them. They provide methods for writing any kind of primitive datatype up to String with arbitrary encoding. All you need to do is use the writeString(...) method and use the read String method on the other side. This way you don't need to convert the String in order to write it into you stream and you don't need to care about how to reconstruct it from the stream.
If you only want to write Strings you can use the BufferedWriter which allows you to only write Strings to an stream, you can use it like this to stick it onto a 'OutputStream'
OutputStreamWriter osw = new OutputStreamWriter(outStream);
BufferedWriter writer = new BufferedWriter(osw);

android : Unable to stop activity

I am new to android. I have a loginActivity which validates a user number and then starts a "searchactivity".
At runtime, I see the search activity coming up (after user is validated) but then android is having problems stopping the loginActivity.
I am getting a "java.lang.runtimeexception: Unable to stop activity {com.insruance/com.insurance.LoginActivity}: android.app.SuperNotCalledException : Activity
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3413)"
I would really appreciate if someone could point to what I am doing wrong.
Code :
public class LoginActivity extends Activity{
DatabaseWrapper myDbHelper;
private String agentNumber;
private OnClickListener btnClickListner = new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
// = new DataBaseHelper();
try {
Log.d("LoginActivity->onClick", "Before findByID");
EditText editText = (EditText)findViewById(R.id.txtUserNumber);
Log.d("LoginActivity->onClick", "After findByID");
agentNumber = editText.getText().toString();
String msg = "";
AgentDbHelper agentHelper = new AgentDbHelper(myDbHelper.getDatabaseHandle());
Log.d("LoginActivity->onClick", "Before agentIDExists");
if (agentHelper.agentIDExists(agentNumber))
msg = "Login success";
else
msg = "Login failed";
Log.d("LoginActivity->onClick", "After agentByID");
myDbHelper.closeDatabase();
myDbHelper = null;
Toast.makeText(getBaseContext(),
"User " + agentNumber + " found!",
Toast.LENGTH_LONG).show();
callSearchActivity();
}
catch(SQLException sqlEx)
{
Log.d("login - onclick", sqlEx.toString());
}
catch (Exception e) {
// TODO: handle exception
Log.d("login - onclick", e.toString());
}
}
};
private void callSearchActivity()
{
Intent intent = new Intent(getBaseContext(), SearchActivity.class);
Bundle bun = new Bundle();
bun.putString("agentNumber", agentNumber);
intent.putExtras(bun);
startActivity(intent);
}
#Override
public void onStop() {
try {
Log.d("In LoginActivity->onStop", "about to close myDbHelper");
if (myDbHelper != null)
{
myDbHelper.closeDatabase();
Log.d("In LoginActivity->onStop", "after myDbHelper is closed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("In LoginActivity->onStop exeption", e.toString());
//e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.login);
Button loginButton = (Button)this.findViewById(R.id.btnLogin);
loginButton.setOnClickListener(btnClickListner);
myDbHelper = new DatabaseWrapper(this);
myDbHelper.openDatabase();
}
catch(Exception e) {
Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}
}
}
A little more digging pointed me to this.
I was not calling super.onStop() within the overriden onStop.
I would have thought that Eclipse would have scripted this line when it created the onStop for me.

Categories

Resources