Bluetooth receive program - Android Studio

Hello.
I`m 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...
JavaScript:
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
}
}
}
Code:
TextView cmd = (TextView)findViewById(R.id.cmd); //Would like to show value in textbox for easier debugging.
Don`t know what to write here to make command executing all the time. (onCreate maybe?).
mmSocket = socket;
mRx = new ArrayList<Byte>();
InputStream tmpIn = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
cmd.setText(//I don`t know what to put in here to display value of tmpIn//);
mmInStream = tmpIn; //Is tmpIn an integer and stores values received from bt? I assume so.
I`m going nust on this one
Thank you fo r help

The code was already there. Under void run, I just had to use strInput string.

Related

Pass variable from one activity to another

I want to show the result activity on the end of the quiz which is working. And then show the scores activity on press of a button on the main activity
Advice I got is to Create a listener for the scores button on Main Activity and add code to launch the Scores Activity with an intent where you pass the score. And then retrieve the bundle on the onCreate method on your ScoresActivity. Can someone help me on this please regarding the code.
MainActivity:
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
myDb.insertData();
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Result:
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
int score;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void getScore()
{
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores:
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Result res = new Result();
res.getScore();
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("Last quiz score:" + " " + score + ".");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scores, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
svvorf said:
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
Click to expand...
Click to collapse
Can you maybe show me where to put this in my code. And help me with the new Result() part

save image from grid view

Hai I need help. How can I save image that choosen from gridView (on the action bar) to device gallery .
Here my code :
Gallery activty
public class GalleryActivity extends AppCompatActivity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(GalleryActivity.this, ViewImageActivity.class);
//int item =(int) parent.getSelectedItemPosition();
intent.putExtra("id", position);
startActivity(intent);
// Toast.makeText(GalleryActivity.this,"" + position,Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(GalleryActivity context) {
mContext = context;
}
public ImageAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(400, 400));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = {
R.drawable.car,
R.drawable.wolf,
R.drawable.dolphin,
R.drawable.cat,
R.drawable.car,
R.drawable.car,
};
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
View image activity
public class ViewImageActivity extends GalleryActivity {
ImageAdapter imageAdapter = new ImageAdapter(this);
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
}

App lags and freeze badly.

is it because of many operations executing from main UI ?
In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}

[Help] Bluetooth app

Hi!
I have some problems with my bluetooth app. I made the setup for a bluetooth server on a Raspberry Pi and I was able to send data to it with my app, but I don't know how to receive data from the server. The server works properly, I tried with the BlueTerm 2 app and I can receive data from it. Can someone help me to implement the receiver in my app?
My code below:
Code:
package com.example.bluetooth1;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:1A:7D:DA:71:14";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("esti un prost");
//Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("cel mai prost");
// Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
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 void onResume() {
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
btAdapter.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
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 void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(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);
}
}
}

Get all information from Android Room Database based on ID

In database Note have id, title and description. I'm passing id from Mainactivity in to the NoteInfoActivity and into the NoteInfoActivity I'd like to get title and description from room database based on that id. What should I add into the NoteInfoActivity? Your help will be appreciated.
NoteDao
Code:
@Dao
public interface NoteDao {
@Insert
void insert(Note note);
@Update
void update(Note note);
@Delete
void delete(Note note);
@Query("DELETE FROM note_table")
void deleteAllNotes();
@Query("SELECT * FROM note_table ORDER BY priority")
LiveData<List<Note>> getAllNotes();
@Query("SELECT * FROM note_table WHERE id =:noteID")
List<Note> getNote(long noteID);
MainActivity
Code:
public class MainActivity extends AppCompatActivity {
private NoteViewModel noteViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final NoteAdapter adapter = new NoteAdapter();
recyclerView.setAdapter(adapter);
noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
@Override
public void onChanged(@Nullable List<Note> notes) {
adapter.setNotes(notes);
}
});
adapter.setOnItemClickListener(new NoteAdapter.OnItemClickListener() {
@Override
public void onItemClick(Note note) {
Intent intent = new Intent(MainActivity.this, NoteInfoActivity.class);
intent.putExtra("NoteID", note.getId());
startActivity(intent);
}
});
}
}
NoteInfoActivity
Code:
public class NoteInfoActivity extends AppCompatActivity {
private static final String TAG = "NoteInfoActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_info);
TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
TextView textViewPriority = findViewById(R.id.textViewPriority);
Intent intent = getIntent();
if (intent != null && intent.hasExtra("NoteID")) {
long noteID = intent.getIntExtra("NoteID", -1);
Log.d(TAG, "onCreate: Note Id Is " + noteID);
} else {
Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources