button not opening new activity - java

I've created 3 buttons. Each should open up different activities. I've tested it on my device and it never opens a new activity. Could it be due to the main.xml file where I've used the onClick feature for the button despite no using it within my main activity.
public class Main extends Activity implements View.OnClickListener{
private Button playButton, rulesButton, aboutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {//when the app starts this method is run
super.onCreate(savedInstanceState);
// Set the layout for fragment_layout.xml
setContentView(R.layout.main_layout);
playButton = (Button) findViewById(R.id.button_play);
playButton.setOnClickListener(this);
rulesButton = (Button) findViewById(R.id.button_rules);
rulesButton.setOnClickListener(this);
aboutButton = (Button) findViewById(R.id.button_about);
aboutButton.setOnClickListener(this);
}
public void buttonPlayClick(){
startActivity(new Intent("com.example.will.sata.openGLActivity"));
}
public void buttonRulesClick(){
startActivity(new Intent("com.example.will.sata.DetailsActivity"));
}
public void buttonAboutClick(){
startActivity(new Intent(""));
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button_play:
buttonPlayClick();
break;
case R.id.button_about:
buttonAboutClick();
break;
case R.id.button_rules:
buttonRulesClick();
break;
}
}
}
AndroidManifest.xml
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.will.sata.DetailsActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.example.will.sata.openGLActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
main.layout.xml
android:id="#+id/button_play"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Play"
android:onClick="PlayGame"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
style="?android:attr/borderlessButtonStyle"
android:focusable="true" />

I have some corrections of your code, I hope it helps:
In main_layout.xml you don't need android:onClick="playGame" because you are using View.OnClickListener in the main class.
You can also use the android:onClick="playGame", but your code in the Main.class would be like this:
public class Main extends Activity {
private Button playButton, rulesButton, aboutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
playButton = (Button) findViewById(R.id.button_play);
rulesButton = (Button) findViewById(R.id.button_rules);
aboutButton = (Button) findViewById(R.id.button_about);
}
public void playGame(View v) {
switch (v.getId())
{
case R.id.button_play:
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
break;
case R.id.button_rules:
Intent intent = new Intent(Main.this, DetailsActivity.class);
startActivity(intent);
break;
}
}
To register a new activity in AndroidManifest.xml you just need to do this
<activity android:name="com.example.will.sata.OpenGLActivity"/>
<activity android:name="com.example.will.sata.DetailsActivity"/>`
To start a new activity from Main.class you have to do this (It is really important to register the Activity first in the AndroidManifest.xml):
Intent intent = new Intent(Main.this, OpenGLActivity.class);
startActivity(intent);
Intent intent = new Intent(Main.this, DetailsActivity.class);
startActivity(intent);
Tip: be careful with the naming conventions

Related

Android: App won't load my splash screen and moves directly to the onboarding screens

I have just gotten into Android app development and have been working on parts of my project in bits and pieces.
I first created my onboarding screens and then made my animated splash screen. However, when I run my application my splash screen does not show and instead loads the onboarding pages first. How can I fix this to make my app first transition through the splash screen before moving on the onboarding screens?
This is my SplashActivity Class code
public class SplashActivity extends AppCompatActivity {
private static int SPLASH_SCREEN = 5000;
// Variables
Animation topAnim;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
// Animations
topAnim = AnimationUtils.loadAnimation(this,R.anim.top_animation);
// Hooks
image = findViewById(R.id.splashScreenLogo);
image.setAnimation(topAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this, OnboardingActivity.class);
startActivity(intent);
finish();
}
}, SPLASH_SCREEN);
}
}
This is my OnboardingActivity Class code
public class OnboardingActivity extends AppCompatActivity {
private OnboardingAdapter onboardingAdapter;
private LinearLayout layoutOnboardingIndicators;
private MaterialButton buttonOnboardingAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
// Onboarding Screens
layoutOnboardingIndicators = findViewById(R.id.layoutOnboardingIndicators);
buttonOnboardingAction = findViewById(R.id.buttonOnboardingAction);
setupOnboardingItems();
final ViewPager2 onboardingViewPager = findViewById(R.id.onboardingViewPager);
onboardingViewPager.setAdapter(onboardingAdapter);
setupOnboardingIndicators();
setCurrentOnboardingIndicator(0);
onboardingViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setCurrentOnboardingIndicator(position);
}
});
buttonOnboardingAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onboardingViewPager.getCurrentItem() + 1 < onboardingAdapter.getItemCount()) {
onboardingViewPager.setCurrentItem(onboardingViewPager.getCurrentItem() + 1);
}
else {
startActivity(new Intent(getApplicationContext(), SignUpActivity.class));
finish();
}
}
});
}
}
Edit - My Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mentalhealthapp">
<application
android:allowBackup="true"
android:icon="#drawable/treen_app_logo"
android:label="treen"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity"></activity>
<activity android:name=".HomeActivity" />
<activity android:name=".SignInActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name=".OnboardingActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
What should I change in my Manifest File?
You need to set the Launch activity as SplashActivity in your AndroidManifest.xml file
<activity
android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

errors in main_activity.java file

cannot find symbol class intent, cannot find...Activity2.class, cannot find...Activity-main
public class MainActivity extends AppCompatActivity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.MyButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Start NewActivity.class
Intent myIntent = new Intent(MainActivity.this,
NewActivity2.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
all the imports precede the above code like import widget button, etc.
Open your Manifest and check if there are entries like these:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity2" />
Overriding method should call super, so it should be:
super.onCreate(savedInstanceState);
and make sure that your NewActivity2 is registered in manifest.

Second button not working

I have 2 buttons, the first one works fine but not the second one(button5). It crashes the app upon clicking.
The error encountered is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I defined the buttons as such in the XML file:
<Button
android:id="#+id/button"
android:layout_width="182dp"
android:layout_height="49dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="135dp"
android:background="#drawable/pay"
android:fontFamily="#font/roboto"
android:text="Login"/>
<Button
android:id="#+id/button5"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="-136dp"
android:fontFamily="#font/roboto"
android:text="#string/create_new_account"
android:textSize="12sp" />
and called it:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button5 = (Button) findViewById(R.id.button5);
}
public void onClick(View v) {
if (v.getId() == R.id.button) {
Intent intent = new Intent(MainActivity.this, detailspage.class);
startActivity(intent);
} else if (v.getId() == R.id.button5) {
Intent intent = new Intent(MainActivity.this, Registration.class);
startActivity(intent);
}
}
My manifest file is:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".detailspage"/>
<activity android:name=".Registration"/>
<activity android:name=".confirmBicycle"></activity>
</application>
I have went through many similar questions and tried different ways of writing the code but to no avail. Thanks for any advice!
button.setOnClickListener(this);
button5.setOnClickListener(this);
You are implementing the interface in your activity but not passing your activity instance to the listener.
i suggest you to try:
Button button5 = (Button) findViewById(R.id.button5);
button5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your code
}
});
I copied your layout and pasted in my layout. Also, I created an activity wherein again I've pasted your code. In my case, it is working fine:
public class Activity1 extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Button button = (Button) findViewById(R.id.button);
Button button5 = (Button) findViewById(R.id.button5);
// this is the only part which I could not find in your code.
button.setOnClickListener(this);
button5.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.button){
Intent intent = new Intent(Activity1.this, SplashActivity.class);
startActivity(intent);
}
else if(view.getId() == R.id.button5){
Intent intent = new Intent(Activity1.this, ActivityLifeCycle.class);
startActivity(intent);
}
}
}

No Activity Found to handle Intent in the class file

I am pretty new to Android. I am learning about passing Intents within activities. Here is my code to pass Intent between 2 activties.
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.btOk);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText etName = (EditText)findViewById(R.id.etName);
String Data = etName.getText().toString();
Intent i = new Intent("com.adhish.passingintentdata.layout2");
Bundle extras = new Bundle();
extras.putString("Name", Data);
i.putExtras(extras);
startActivityForResult(i,1);
}
});
}
layout2.java
public class layout2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout2);
String myName = null;
Bundle extras = getIntent().getExtras();
if(extras != null)
{
myName = extras.getString("Name");
}
TextView tvData = (TextView)findViewById(R.id.tvData);
tvData.setText(myName);
}
}
Manifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".layout2"
android:label="#string/title_activity_layout2"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.adhish.passingintentdata.MainActivity" />
</activity>
When i run this code and click on the OK button to pass the data, my app crashes with a fatal error.
The error is:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.adhish.passingintentdata.layout2 (has extras) }
Please give me a detailed help about working with this issue, because I am new to Android.
Thanks.
Use com.adhish.passingintentdata.MainActivity as Action string for creating Intent to launch layout2 Activity :
Intent i = new Intent("com.adhish.passingintentdata.layout2");
and in Manifast add intent-filter for layout2 Activity:
<intent-filter>
<action android:name="com.adhish.passingintentdata.layout2" />
</intent-filter>
Use this intent instead:
Intent i = new Intent(MainActivity.this, layout2.class);

Android activity only works properly if it is the main activity?

When I set an activity to be the launcher it works fine, however when I launch this activity from another activity, it will open fine displaywise, some of the functionality works and some of it does not?! Very confusing for me.
Basically if I open it as the Launcher data can be sent and received over serial. But if I open it from another activity instead absolute crap gets sent over serial and nothing is coming back. However some parts work such as establishing the serial connection?!
In the launching activity this is the code to open the activity I want:
public void openTextTerminal(View view)
{
Intent intent = new Intent(this, TextBoxActivity.class);
startActivity(intent);
}
This is the manifest:
(I don't think I even need the intent filter?!)
<activity
android:name="com.example.TextBoxActivity"
android:label="#string/title_activity_text_box" >
<intent-filter>
<action android:name="android.intent.action.TextBoxActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Full Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:installLocation="auto"
android:versionCode="49"
android:versionName="1.0.48" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="12" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.permission.RUN_SCRIPT"
android:description="#string/permdesc_run_script"
android:label="#string/perm_run_script"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<permission
android:name="com.example.permission.APPEND_TO_PATH"
android:description="#string/permdesc_append_to_path"
android:label="#string/perm_append_to_path"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<permission
android:name="com.example.permission.PREPEND_TO_PATH"
android:description="#string/permdesc_prepend_to_path"
android:label="#string/perm_prepend_to_path"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/application_terminal" >
<activity
android:name="com.example.Term"
android:configChanges="keyboard|keyboardHidden|orientation"
android:launchMode="singleTask"
android:theme="#style/Theme"
android:windowSoftInputMode="adjustResize|stateAlwaysVisible" >
<intent-filter>
<action android:name="android.intent.action.TERM" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity-alias
android:name="com.example.TermInternal"
android:exported="false"
android:targetActivity="Term" >
<intent-filter>
<action android:name="com.example.private.OPEN_NEW_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="com.example.private.SWITCH_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity-alias>
<activity
android:name="com.example.RemoteInterface"
android:excludeFromRecents="true" >
<intent-filter>
<action android:name="com.example.OPEN_NEW_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity-alias
android:name="com.example.RunScript"
android:permission="com.example.permission.RUN_SCRIPT"
android:targetActivity="RemoteInterface" >
<intent-filter>
<action android:name="com.example.RUN_SCRIPT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity-alias>
<activity
android:name="com.example.TermPreferences"
android:label="#string/preferences" />
<activity
android:name="com.example.WindowList"
android:label="#string/window_list" />
<service android:name="com.example.TermService" />
<activity
android:name="com.example.MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.TextBoxActivity"
android:label="#string/title_activity_text_box" >
<intent-filter>
<action android:name="android.intent.action.TextBoxActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.SerialTerminalActivity"
android:label="#string/title_activity_serial_terminal"
android:screenOrientation="landscape" >
</activity>
</application>
</manifest>
I replicated the code in a program on it's own (ie using an activity to launch the second activity without my other unrelated classes) and it works fine. I just copied and pasted. I did a diff on all the files and there is practically nothing different, just unrelated things in the manifest as far as I can see. I'll just go through the whole manifest tomorrow (I spent a whole day debugging just to find this bug) and rewrite it or something.
I was just curious as to how it can appear that everything is working normally but that it is not. I would have thought once I launch the activity everything is exactly the same no matter how I launch it (as I am passing nothing).
May be passing wrong context, here is full code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener, AdapterConnectionListener, DataListener{
private Spinner mBaudSpinner;
private Spinner mDataSpinner;
private Spinner mParitySpinner;
private Spinner mStopSpinner;
private Spinner mDeviceSpinner;
private Button mConnect;
private ArrayList<String> mDeviceOutputs;
private ArrayList<USB2SerialAdapter> mDeviceAdapters;
private ArrayAdapter<CharSequence> mDeviceSpinnerAdapter;
private USB2SerialAdapter mSelectedAdapter;
private TextView mCurrentSettings;
private Button mUpdateSettings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mConnect = (Button)findViewById(R.id.deviceConnect);
mConnect.setOnClickListener(this);
mUpdateSettings = (Button)findViewById(R.id.updateSettings);
mUpdateSettings.setOnClickListener(this);
mBaudSpinner = (Spinner)findViewById(R.id.baudSpinner);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mBaudSpinner.setAdapter(adapter);
String[] tempArray = SlickUSB2Serial.BAUD_RATES;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mBaudSpinner.setSelection(SlickUSB2Serial.BaudRate.BAUD_9600.ordinal());
mDataSpinner = (Spinner)findViewById(R.id.dataSpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDataSpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.DATA_BITS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mDataSpinner.setSelection(SlickUSB2Serial.DataBits.DATA_8_BIT.ordinal());
mParitySpinner = (Spinner)findViewById(R.id.paritySpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mParitySpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.PARITY_OPTIONS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mParitySpinner.setSelection(SlickUSB2Serial.ParityOption.PARITY_NONE.ordinal());
mStopSpinner = (Spinner)findViewById(R.id.stopSpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mStopSpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.STOP_BITS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mStopSpinner.setSelection(SlickUSB2Serial.StopBits.STOP_1_BIT.ordinal());
mDeviceAdapters = new ArrayList<USB2SerialAdapter>();
mDeviceOutputs = new ArrayList<String>();
mDeviceSpinner = (Spinner)findViewById(R.id.deviceSpinner);
mDeviceSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
mDeviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDeviceSpinner.setAdapter(mDeviceSpinnerAdapter);
mDeviceSpinner.setOnItemSelectedListener(this);
mCurrentSettings = (TextView)findViewById(R.id.currentSettings);
SlickUSB2Serial.initialize(this);
}
public void openTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, Term.class);
startActivity(intent);
}
public void openTextTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, TextBoxActivity.class);
startActivity(intent);
}
public void openSerialTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, SerialTerminalActivity.class);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
changeSelectedAdapter(mDeviceAdapters.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void changeSelectedAdapter(USB2SerialAdapter adapter){
Toast.makeText(this, "in changeselectedadapter", Toast.LENGTH_SHORT).show();
//if(mSelectedAdapter!=null){
//mDeviceOutputs.set(mDeviceSpinnerAdapter.getPosition(mSelectedAdapter.getDeviceId()+""),mReceiveBox.getText().toString());
mSelectedAdapter = adapter;
mBaudSpinner.setSelection(adapter.getBaudRate().ordinal());
mDataSpinner.setSelection(adapter.getDataBit().ordinal());
mParitySpinner.setSelection(adapter.getParityOption().ordinal());
mStopSpinner.setSelection(adapter.getStopBit().ordinal());
updateCurrentSettingsText();
//mReceiveBox.setText(mDeviceOutputs.get(mDeviceSpinner.getSelectedItemPosition()));
Toast.makeText(this, "Adapter switched toooo: "+adapter.getDeviceId()+"!", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
if(v==mConnect){
SlickUSB2Serial.autoConnect(this);
if(mSelectedAdapter==null){
Toast.makeText(this, "no adapters detected", Toast.LENGTH_SHORT).show();
return;
//String data = mSendBox.getText().toString() + "\r\n";
// mSelectedAdapter.sendData(data.getBytes());
//mSendBox.setText("");
}
Intent intent = new Intent(this, SerialTerminalActivity.class);
startActivity(intent);
}
else if(v==mUpdateSettings){
if(mSelectedAdapter==null){
return;
}
mSelectedAdapter.setCommSettings(BaudRate.values()[mBaudSpinner.getSelectedItemPosition()],
DataBits.values()[mDataSpinner.getSelectedItemPosition()],
ParityOption.values()[mParitySpinner.getSelectedItemPosition()],
StopBits.values()[mStopSpinner.getSelectedItemPosition()]);
updateCurrentSettingsText();
Toast.makeText(this, "Updated Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAdapterConnected(USB2SerialAdapter adapter) {
adapter.setDataListener(this);
mDeviceAdapters.add(adapter);
mDeviceOutputs.add("");
mDeviceSpinnerAdapter.add(""+adapter.getDeviceId());
mDeviceSpinner.setSelection(mDeviceSpinnerAdapter.getCount()-1);
Toast.makeText(this, "Adapter: "+adapter.getDeviceId()+" Connected!", Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Baud: "+adapter.getBaudRate()+" Connected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterConnectionError(int error, String msg) {
// TODO Auto-generated method stub
if(error==AdapterConnectionListener.ERROR_UNKNOWN_IDS){
final AlertDialog dialog = new AlertDialog.Builder(this)
.setIcon(0)
.setTitle("Choose Adapter Type")
.setItems(new String[]{"Prolific", "FTDI"}, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int optionSelected){
if(optionSelected==0)
{
SlickUSB2Serial.connectProlific(MainActivity.this);
}
else
{
SlickUSB2Serial.connectFTDI(MainActivity.this);
}
}
}).create();
dialog.show();
return;
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void updateCurrentSettingsText(){
mCurrentSettings.setText("Current Settings Areeee: "+mBaudSpinner.getSelectedItem().toString()
+", "+mDataSpinner.getSelectedItem().toString()
+", "+mParitySpinner.getSelectedItem().toString()
+", "+mStopSpinner.getSelectedItem().toString());
}
#Override
public void onDataReceived(int arg0, byte[] arg1) {
// TODO Auto-generated method stub
Toast.makeText(this, "IN ONDATARECIEVED OHOH", Toast.LENGTH_SHORT).show();
}
public void onDestroy() {
SlickUSB2Serial.cleanup(this);
super.onDestroy();
}
}
Here you have used this for the context, first you should know about the different contexts.
this refers to your current object. In your case you must have implemented the intent in an inner class, or some ClickEvent, and thats what it points to.
Activity.this points to the instance of the Activity you are currently in.
getApplicationContext() refers to the application's context.
Now if the this context is directly under the oncreate() of the activity and not in any other class or some button's onClick() event, then it the same as that of the Activity's context.
But it is preferred to use getApplicationContext(), as the Activity's Context dies, when the same activity finishes.
I found the culprit in onCreate() of the launching activity, it was a library call. All I had to do was move it from the launching activity to the called activity. That will teach me to just follow the API instructions blindly.
So I had SlickUSB2Serial.initialize(this); in the wrong activity.
initialize(android.content.Context context)
initialize must be called when your app first starts up (in onCreate).

Categories

Resources