1

im creating an app for reading and writing a nfc tag, for that I created a tab menu, with 4 tabs. this app hava a custom title bar, and a image on the background.
im trying to run this app in an api 16.
when tab3 is pressed everything appear correctly , my custom title bar, my background and the 4 tabs below. Inside this tab I have a textbox, and a button, on button click the text in the textbox should be passed to the nfc tag, and if not it should read the tag data.
what happens is that when I click in the buttom instead of writing to the tag, its reading, and when it reads the tag, the activity that is started is the tags activity, but the layout is wrong, it only appears the activity title defined in the manifest, a black blackground and the textbox and button. then if I click in the button to write to the tag , it works, and and reads the tags if button is not clicked.
Now ive created a fourth tab that has a button inside, and if the button is clicked it starts a new activity, and this tagsactivity works well. Is the problem related to the use of tagsactivity in a api16, when this class is deprecated after api13? Or is it another thing that a im missing.
here is tabs2

 import android.app.LocalActivityManager;
   import android.content.Intent;
 import android.os.Bundle;
 import android.view.KeyEvent;
 import android.view.View;
 import android.view.View.OnKeyListener;
 import android.view.Window;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.TabHost;

 public class Tabs2 extends android.app.TabActivity{
public TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.activity_tabs);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
        // Get the tabHost
    this.tabHost = getTabHost();


    Button btentrar= (Button) findViewById(R.id.titlebarRefreshBtn);

       btentrar.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                setResult(2);
                finish();
            }
        }); 

    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch the first Activity for the tab (to be reused)
    intent = new Intent().setClass(this, FirstGroup.class);

    // Initialize a TabSpec for the first tab and add it to the TabHost
    spec = tabHost.newTabSpec("Opcções").setIndicator("FirstGroup",
            getResources().getDrawable(R.drawable.settingsicon)) // Replace null with R.drawable.your_icon to set tab icon
                    .setContent(intent);
    tabHost.addTab(spec);

        // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, SecondActivityGroup.class);

    // Initialize a TabSpec for the second tab and add it to the TabHost
    spec = tabHost.newTabSpec("Tags passadas").setIndicator("Tags Passadas",
            getResources().getDrawable(R.drawable.writedocumenticon)) // Replace null with R.drawable.your_icon to set tab icon
                    .setContent(intent);
    tabHost.addTab(spec);

     // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, ThirdActivityGroup.class);

        // Initialize a TabSpec for the second tab and add it to the TabHost
        spec = tabHost.newTabSpec("Read and write").setIndicator("Ler e escrever",
                getResources().getDrawable(R.drawable.checkiconm)) // Replace null with R.drawable.your_icon to set tab icon
                        .setContent(intent);
        tabHost.addTab(spec);


        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, FourthActivityGroup.class);

        // Initialize a TabSpec for the second tab and add it to the TabHost
        spec = tabHost.newTabSpec("Read and write v2").setIndicator("Ler e escrever v2",
                getResources().getDrawable(R.drawable.checkiconm)) // Replace null with R.drawable.your_icon to set tab icon
                        .setContent(intent);
        tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
}
}

here is thirdactivitygroup that extends activitygroup

import java.util.ArrayList;

import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ThirdActivityGroup extends ActivityGroup {

    // Keep this in a static variable to make it accessible for all the nested activities, lets them manipulate the view
public static ThirdActivityGroup group;

    // Need to keep track of the history if you want the back-button to work properly, don't use this if your activities requires a lot of memory.
private ArrayList<View> history;

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.history = new ArrayList<View>();
      group = this;

          // Start the root activity withing the group and get its view
      View view = getLocalActivityManager().startActivity("TagsActivity", new
                                         Intent(this,TagsActivity.class)
                                          .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                                        .getDecorView();

          // Replace the view of this ActivityGroup
      replaceView(view);

   }

public void replaceView(View v) {
            // Adds the old one to history
    history.add(v);
            // Changes this Groups View to the new View.
    setContentView(v);
}

public void back() {
    if(history.size() > 0) {
        history.remove(history.size()-1);
        setContentView(history.get(history.size()-1));
    }else {
        finish();
    }
}

public void onBackPressed() {
    ThirdActivityGroup.group.back();
    return;
}

}

and here is fourthactivitygroup

import java.util.ArrayList;

import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
 import android.view.View;

public class FourthActivityGroup extends ActivityGroup {

    // Keep this in a static variable to make it accessible for all the nested activities, lets them manipulate the view
public static FourthActivityGroup group;

    // Need to keep track of the history if you want the back-button to work properly, don't use this if your activities requires a lot of memory.
private ArrayList<View> history;

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.history = new ArrayList<View>();
      group = this;

          // Start the root activity withing the group and get its view
      View view = getLocalActivityManager().startActivity("Teste", new
                                        Intent(this,Teste.class)
                                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                                        .getDecorView();

          // Replace the view of this ActivityGroup
      replaceView(view);

   }

public void replaceView(View v) {
            // Adds the old one to history
    history.add(v);
            // Changes this Groups View to the new View.
    setContentView(v);
}

public void back() {
    if(history.size() > 0) {
        history.remove(history.size()-1);
        setContentView(history.get(history.size()-1));
    }else {
        finish();
    }
}

public void onBackPressed() {
    FourthActivityGroup.group.back();
    return;
}

}

here is teste

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class Teste extends Activity {

    // Keep this in a static variable to make it accessible for all the nested activities, lets them manipulate the view

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_teste);

        Button btnfc= (Button) findViewById(R.id.button1);

           btnfc.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    startActivity(new Intent(Teste.this, TagsActivity.class));  
                }
            }); 

   }

}

and here is the tagsactivity

public class TagsActivity extends Activity {




private NfcAdapter mNfcAdapter;

private Button mEnableWriteButton;
private EditText mTextField;
private ProgressBar mProgressBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tags);
     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
    mTextField = (EditText) findViewById(R.id.text_field);

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mProgressBar.setVisibility(View.GONE);

    mEnableWriteButton = (Button) findViewById(R.id.enable_write_button);
    mEnableWriteButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            setTagWriteReady(!isWriteReady);
            mProgressBar.setVisibility(isWriteReady ? View.VISIBLE : View.GONE);
        }
    });

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        Toast.makeText(this, "Sorry, NFC is not available on this device", Toast.LENGTH_SHORT).show();
        finish();
    }


}

private boolean isWriteReady = false;

/**
 * Enable this activity to write to a tag
 * 
 * @param isWriteReady
 */
public void setTagWriteReady(boolean isWriteReady) {
    this.isWriteReady = isWriteReady;
    if (isWriteReady) {
        IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };
        mNfcAdapter.enableForegroundDispatch(TagsActivity.this, NfcUtils.getPendingIntent(TagsActivity.this),
                writeTagFilters, null);
    } else {
        // Disable dispatch if not writing tags
        mNfcAdapter.disableForegroundDispatch(TagsActivity.this);
    }
    mProgressBar.setVisibility(isWriteReady ? View.VISIBLE : View.GONE);
}

@Override
public void onNewIntent(Intent intent) {
    // onResume gets called after this to handle the intent
    setIntent(intent);
}

@Override
public void onResume() {
    super.onResume();
    if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
        processWriteIntent(getIntent());
    } else if (!isWriteReady
            && (NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED
                    .equals(getIntent().getAction()))) {
        processReadIntent(getIntent());
    }
}

private static final String MIME_TYPE = "application/com.smartcom.onetagv4";

/**
 * Write to an NFC tag; reacting to an intent generated from foreground
 * dispatch requesting a write
 * 
 * @param intent
 */
public void processWriteIntent(Intent intent) {
    if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {

        Tag detectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String tagWriteMessage = mTextField.getText().toString();
        byte[] payload = new String(tagWriteMessage).getBytes();

        if (detectedTag != null && NfcUtils.writeTag(
                NfcUtils.createMessage(MIME_TYPE, payload), detectedTag)) {

            Toast.makeText(this, "Wrote '" + tagWriteMessage + "' to a tag!", 
                    Toast.LENGTH_LONG).show();
            setTagWriteReady(false);
        } else {
            Toast.makeText(this, "Write failed. Please try again.", Toast.LENGTH_LONG).show();
        }
    }
}

public void processReadIntent(Intent intent) {
    List<NdefMessage> intentMessages = NfcUtils.getMessagesFromIntent(intent);
    List<String> payloadStrings = new ArrayList<String>(intentMessages.size());

    for (NdefMessage message : intentMessages) {
        for (NdefRecord record : message.getRecords()) {
            byte[] payload = record.getPayload();
            String payloadString = new String(payload);

            if (!TextUtils.isEmpty(payloadString))
                payloadStrings.add(payloadString);
        }
    }

    if (!payloadStrings.isEmpty()) {
        String content =  TextUtils.join(",", payloadStrings);
        Toast.makeText(TagsActivity.this, "Read from tag: " + content,
                Toast.LENGTH_LONG).show();

    }
}



}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Hugo Silva
  • 23
  • 1
  • 10
  • Please clean up your question, there is a lot of unnecessary information. Why did you assume that it fails, can you paste a copy of your log at the point where you code fails? – ılǝ Nov 14 '12 at 01:39
  • @ile im sorry, but i cant run this nfc app on eclipse, because it tells me that this device doesnt suport nfc.it works but not the way i want. – Hugo Silva Nov 14 '12 at 02:10
  • by "run app on eclipse" do you mean you can't run it on an Android virtual device? I am confused, can you please explain more clearly what is the exact problem that you are experiencing? – ılǝ Nov 14 '12 at 02:24
  • @ile i can run the app, but if tab3 is pressed there is a message saying "Sorry, NFC is not available on this device", so i passed the app to a android phone running version 4.0. i can change between tabs 1,2 and 4.Om the tab4 the same appens again, if i click on the button it appears the same message. ive redone the question. is the problem related to the tabactivity being deprecated on api16. – Hugo Silva Nov 14 '12 at 02:43
  • I am sorry, obviously the reason is not in nfc, I cant think of a solution, hope someone else could help – ılǝ Nov 14 '12 at 11:49
  • no, the problem lies in the connection between the tabactivity, tabgroup running on android version superior to api 13.But i dont have sure if that realy is the problem.Because the metohod tabactivity is deprecated after api13, the same goes for activitygroup, althoug the tabs appear correctly in api16, there might be some compatabilities issues....but the same question remains, is this the problems, does running deprecated methods on api16 create problems... – Hugo Silva Nov 14 '12 at 12:41
  • why dont you switch from tabactivity to fragments, which seems the most logical thing - http://stackoverflow.com/questions/8140691/android-api-tabactivity-deprecation – ılǝ Nov 14 '12 at 12:43
  • yes, im gone try that aproach, but before i do that i am tryint to teste my app in an api less than the 13 – Hugo Silva Nov 14 '12 at 14:04
  • ok so the problems is not the deprecated methods...this will stay for a few days to see, if anyone can explain me ...after that i will close this. – Hugo Silva Nov 14 '12 at 17:31
  • i ve decided to go another way, because this app is for my final work at University. But i will try using fragments once i can, and see if that resolve my problem. – Hugo Silva Nov 15 '12 at 11:25

1 Answers1

0

Use the linked example to rebuild your application. A suggestion: you have problems on using tabs, so as first task build the user interface. When it correctly works, add your NFC code.

rosco
  • 939
  • 9
  • 16
  • Hi, thanks for your help , let try this way, you have a button, that onclick startactivity apple, when this activity is lunched, in my case , it only appear the text, and not the tabs, i.e. the layout shouldhave appear the tabs and the text, but not. – Hugo Silva Nov 18 '12 at 00:06