1

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();
}

}
Paul
  • 5,756
  • 6
  • 48
  • 78
  • which context are you passing in the intent.? – Sahil Mahajan Mj Dec 13 '12 at 09:51
  • I am not sure, i'm quite new to this. I am probably passing the wrong context. I don't really know what to put apart from "this" when opening an intent. i'll edit my original post to show you the full code to see if you can see. Thanks – Paul Dec 13 '12 at 10:37
  • Is it something like I should be calling .this instead of just saying this? The context is really confusing me, I don't know what I am currently passing and what it represents, I thought it would be the activities conext without me having to specify the activities name – Paul Dec 13 '12 at 10:49
  • yes, you should pass the context of the activity like **MyActivity.this**. – Sahil Mahajan Mj Dec 13 '12 at 11:25
  • Is there any difference between this and MyActivity.this as the method containing the intent is inside the activity anyway? Context really confuses me. – Paul Dec 13 '12 at 11:44

2 Answers2

1

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.

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
  • Thank you,very informative. Although it was not the issue in this case I did not know this information well and you will help me avoid issues in the future. I had been avoiding getApplicationContext due to reading this http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context – Paul Dec 13 '12 at 12:01
0

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).
Paul
  • 5,756
  • 6
  • 48
  • 78