I have search and could seem to find anything close to the issue I am having so I figured I would ask.
I have a Dashboard layout
This is all working correctly
What I want to do is have it work as shown below ( I have the Tabhost defined but I had to setup the class to extend TabActivity which breaks the ActionBar navigation )
The tabs correctly switch but it will not allow me to use any of the buttons on the action bar, and its not pulling the information correctly like it should be
the above works correctly. So I guess my question is how can I correctly add the TabHost to my classes and also have it Extend or Implement the Dashboard code? I have tried extends TabActivity implements Dashboard with no luck.
Here is my code thus far
Dashboard.java
package com.ondrovic.bbym;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class Dashboard extends Activity {
public static final boolean usePrettyGoodSolution = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onDestroy() {
super.onDestroy();
}
public void onPause() {
super.onPause();
}
public void onRestart() {
super.onRestart();
}
public void onResume() {
super.onResume();
}
public void onStart() {
super.onStart();
}
public void onStop() {
super.onStop();
}
public void onClickHome(View v) {
goHome(this);
}
public void onClickUpdate(View v) {
//startActivity(new Intent(getApplicationContext(), Update.class));
}
public void onClickAbout(View v) {
//startActivity(new Intent(getApplicationContext(), About.class));
}
public void goHome(Context context) {
final Intent intent = new Intent(context, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
#Override
public void setContentView(int layoutID) {
if (!usePrettyGoodSolution) {
super.setContentView(layoutID);
return;
}
Configuration c = getResources().getConfiguration();
int size = c.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
boolean isLarge = (size == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean isXLarge = (size == Configuration.SCREENLAYOUT_SIZE_XLARGE);
boolean addFrame = isLarge || isXLarge;
// if (isLarge) System.out.println ("Large screen");
// if (isXLarge) System.out.println ("XLarge screen");
int finalLayoutId = addFrame ? R.layout.large : layoutID;
super.setContentView(finalLayoutId);
if (addFrame) {
LinearLayout frameView = (LinearLayout) findViewById(R.id.frame);
if (frameView != null) {
// If the frameView is there, inflate the layout given as an
// argument.
// Attach it as a child to the frameView.
LayoutInflater li = ((Activity) this).getLayoutInflater();
View childView = li.inflate(layoutID, null);
if (childView != null) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0F);
frameView.addView(childView, lp);
// childView.setBackgroundResource (R.color.background1);
}
}
}
}
public void setTitleFromActivityLabel(int textViewID) {
TextView tv = (TextView) findViewById(textViewID);
if (tv !=null) {
tv.setText(getTitle());
}
}
}
Individual.java
package com.ondrovic.bbym;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Individual extends TabActivity {
public void onCreate(Bundle savedSate) {
super.onCreate(savedSate);
setContentView(R.layout.individual);
TabHost tabHost = getTabHost();
TabSpec attspec = tabHost.newTabSpec("ATT");
attspec.setIndicator("AT&T", getResources().getDrawable(R.drawable.icons_att_tab));
Intent attIntent = new Intent(this, Individual_ATT.class);
attspec.setContent(attIntent);
TabSpec sprspec = tabHost.newTabSpec("SPRINT");
sprspec.setIndicator("SPRINT", getResources().getDrawable(R.drawable.icons_sprint_tab));
Intent sprIntent = new Intent(this, Individual_SPRINT.class);
sprspec.setContent(sprIntent);
TabSpec vzwspec = tabHost.newTabSpec("VERIZON");
vzwspec.setIndicator("VERIZON", getResources().getDrawable(R.drawable.icons_verizon_tab));
Intent vzwIntent = new Intent(this, Individual_VERIZON.class);
vzwspec.setContent(vzwIntent);
tabHost.addTab(attspec);
tabHost.addTab(sprspec);
tabHost.addTab(vzwspec);
}
}
Here is my individual.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/background1"
android:orientation="vertical" >
<include layout="#layout/title_bar" />
<include layout="#layout/tabs" />
</LinearLayout>
If there is any other code that needs to be post please let me know and thanks for the assistance
So I figured it out by doing the following. Even though there is probably a better way here is what I've got
Individual.java
package com.ondrovic.bbym;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Individual extends Dashboard {
TabHost mTabs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.individual);
setTitleFromActivityLabel(R.id.title_text);
mTabs = (TabHost) findViewById(android.R.id.tabhost);
LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, false);
mLocalActivityManager.dispatchCreate(savedInstanceState);
mTabs.setup(mLocalActivityManager);
TabSpec attspec = mTabs.newTabSpec("ATT");
attspec.setIndicator("AT&T", getResources().getDrawable(R.drawable.icons_att_tab));
Intent attIntent = new Intent(this, Individual_ATT.class);
attspec.setContent(attIntent);
TabSpec sprintspec = mTabs.newTabSpec("SPRINT");
sprintspec.setIndicator("SPRINT", getResources().getDrawable(R.drawable.icons_sprint_tab));
Intent sprintIntent = new Intent(this, Individual_SPRINT.class);
sprintspec.setContent(sprintIntent);
TabSpec verizonspec = mTabs.newTabSpec("VERIZON");
verizonspec.setIndicator("VERIZON", getResources().getDrawable(R.drawable.icons_verizon_tab));
Intent verizonIntent = new Intent(this, Individual_ATT.class);
verizonspec.setContent(verizonIntent);
mTabs.addTab(attspec);
mTabs.addTab(sprintspec);
mTabs.addTab(verizonspec);
}
}
Here's the result everything is working :-)
Related
I am doing an application with a friend and we are kind of stuck. I have alredy manage to have a multiple line LisView and ive done a custom adapter for it. What this application does is register a car from an other activity and when the Submit button is clicked we want to add 3 items from the car to the ListView we have in a Tabbed Activity. I've tried several things with Intent and Bundle to get the information and then put it in, but it gives a null error.
This is my Project untill now:
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CarType.class);
MainActivity.this.startActivity(intent);
}
});
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPageAdapter(getSupportFragmentManager(),
MainActivity.this));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Fragment fragment = null;
if(tab.getPosition()==0) {
PageFragment pageFragment = new PageFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, pageFragment ).commit();
}
if(tab.getPosition()==1){
SecondPageFragment secondPageFragment = new SecondPageFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container,secondPageFragment).commit();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Page Fragment:
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class PageFragment extends ListFragment {
String[] cars ;
String[] modelo ;
String[] placas ;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
public PageFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle intent = getActivity().getIntent().getExtras();
cars = new String[]{intent.getString("marca")};
modelo = new String[]{intent.getString("modelo")};
placas = new String[]{intent.getString("placas")};
View view = inflater.inflate(R.layout.activity_page_fragment, container, false);
Adapter adapter = new Adapter(getActivity(), cars, modelo, placas);
ListView listView = (ListView) view.findViewById(android.R.id.list);
listView.setAdapter(adapter);
return view;
}
}
Adapter:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class Adapter extends ArrayAdapter<String> {
String [] cars ;
String [] modelo ;
String [] placas ;
Context c;
LayoutInflater inflater;
public Adapter(Context context, String[] cars, String[] modelo, String[] placas){
super(context, R.layout.single_row, cars);
this.c=context;
this.cars=cars;
this.modelo=modelo;
this.placas=placas;
}
public class ViewHolder{
TextView cars;
TextView model;
TextView placas;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.single_row,null);
}
final ViewHolder holder = new ViewHolder();
holder.cars=(TextView)convertView.findViewById(R.id.textView2);
holder.model=(TextView)convertView.findViewById(R.id.textView3);
holder.placas=(TextView)convertView.findViewById(R.id.textView4);
holder.cars.setText(cars[position]);
holder.model.setText(modelo[position]);
holder.placas.setText(placas[position]);
return convertView;
}
}
CarType: this is the form of which I want to get the information to the List View
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.*;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class CarType extends AppCompatActivity {
ImageButton androidImageButton;
ImageView imageView;
static final int CAM_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_type);
final EditText etMarca = (EditText)findViewById(R.id.etMarca);
final EditText etModelo = (EditText)findViewById(R.id.etModelo);
final EditText etPlacas = (EditText)findViewById(R.id.etPlacas);
final EditText etColor = (EditText)findViewById(R.id.etColor);
final CheckBox cbCamioneta = (CheckBox)findViewById(R.id.cbCamioneta);
final CheckBox cbCar = (CheckBox)findViewById(R.id.cbCar);
final boolean checkStatus = cbCamioneta.isChecked();
Button bSubmit = (Button)findViewById(R.id.bSubmit);
assert bSubmit != null;
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Adapter.class);
intent.putExtra("marca", etMarca.getText().toString());
intent.putExtra("modelo", etModelo.getText().toString());
intent.putExtra("placas", etPlacas.getText().toString());
intent.putExtra("color", etColor.getText().toString());
intent.putExtra("camioneta", cbCamioneta.getText().toString());
intent.putExtra("car", cbCar.getText().toString());
intent.putExtra("checkboxstatus", checkStatus);
startActivity(intent);
final String modelo = etModelo.getText().toString();
final String marca = etMarca.getText().toString();
final String placas = etPlacas.getText().toString();
final String color = etColor.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(CarType.this, MainActivity.class);
CarType.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(CarType.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
CarRegisterRequest carregisterRequest = new CarRegisterRequest(marca, modelo, placas, color, responseListener);
RequestQueue queue = Volley.newRequestQueue(CarType.this);
queue.add(carregisterRequest);
}
});
androidImageButton = (ImageButton) findViewById(R.id.image_button_android);
imageView = (ImageView) findViewById(R.id.Final_picture);
androidImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(camera_intent, CAM_REQUEST);
}
});
}
private File getFile(){
File folder = new File ("sdcard/camera_app");
if (!folder.exists()){
folder.mkdir();
}
File image_file = new File(folder, "cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String path = "sdcard/camera_app/cam_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
After this I have an xml file for my page fragment which only includes a ListView and I have a "single_row.xml" which is the format in which is the multiline ListView.
Any Help will be very appreciated, I am quite new to Android and to this site, so I apologize if I dont get an answer directly.
Thank you very much.
It's pretty easy how Activities communicate in android
You need to startActivityForResult(intent, requestCode) from the MainActivity once you started the activity for result, you will need to wait for the result in the same Activity (MainActivity) and you will get the result in your onActivityResult(int requestCode, int resultCode, Intent data) along with all the data in that intent.
public class MainActivity extends AppCompatActivity {
private static final int RQ_CAR = 1;
....
....
// Open the second activity
Intent intent = new Intent(MainActivity.this, CarType.class);
startActivityForResult(intent, RQ_CAR);
....
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RQ_CAR && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
// Extract data and do whatever you want
}
}
}
but where can I assign the Bundle in the intent and set that resultCode to be OK?
In your second Activity (CarType), you will need to do that manually
Intent intent = new Intent();
Bundle extras = new Bundle();
extras.put....(); // put all your data here
intent.putExtras(extras);
setResult(Activity.RESULT_OK, intent);
I have two activity "Data" and "OpenedClass" when i create an Intent to redirect me to an other activity it doesn't work
Data activity
package com.example.androidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Data extends Activity implements OnClickListener {
EditText sendET;
Button start,startFor;
TextView gotAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
}
private void initialize()
{
sendET= (EditText) findViewById(R.id.etSend);
startFor = (Button) findViewById(R.id.bSAFR);
start = (Button) findViewById(R.id.bSA);
gotAnswer = (TextView) findViewById(R.id.tvGot);
start.setOnClickListener(this);
startFor.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSA:
String bread = sendET.getText().toString();
Bundle basket = new Bundle();
basket.putString("key", bread);
Intent a = new Intent(Data.this,OpenedClass.class);
a.putExtras(basket);
startActivity(a);
break;
case R.id.bSAFR:
break;
}
}
}
And Opened Class Activity
package com.example.androidapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class OpenedClass extends Activity implements OnClickListener , OnCheckedChangeListener {
TextView question , test;
Button returnData;
RadioGroup selection;
String gotBread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
initialize();
Bundle b = getIntent().getExtras();
gotBread = b.getString("key");
question.setText(gotBread);
}
private void initialize()
{
question= (TextView) findViewById(R.id.tvQuestion);
test = (TextView) findViewById(R.id.tvText);
returnData = (Button) findViewById(R.id.bReturn);
selection = (RadioGroup) findViewById(R.id.rgAnswers);
returnData.setOnClickListener(this);
selection.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rCrazy:
break;
case R.id.rSerious:
break;
case R.id.rBoth:
break;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
here is the manifest
<activity
android:name=".Data"
android:label="#string/app_name" >
</activity>
<activity
android:name=".OpenedClass"
android:label="#string/app_name" >
</activity>
the button doesn't redirect me to the second activity , help me please
You forgot to call initialize method after setContentView on your Data Activity, so the Listener's are not being registered on Button's. Like:
public class Data extends Activity implements OnClickListener {
EditText sendET;
Button start,startFor;
TextView gotAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
initialize();
}
// Rest of your code...
}
Try this from your Data Activity:
Intent intent = new Intent(mContext, OpenedClass.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(basket);
mContext.startActivity(intent);
Where mContext is defined in your Data Activity as:
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
initialize();
// Other codes here.
}
In your Data Activity,your initialize() did not call.
Im trying to use viewPager so I want to change my class from an activity to fragment, but Im getting alot of errors, so can you tell me whats wrong and what I need to do?
Here is my original activity :
package com.pickapp.pachu.pickapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
import java.util.Random;
public class MainScreen extends Activity implements OnClickListener {
private TitlesDB titles;
private Button getPickUpLine;
private TextView pickUpLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
titles = new TitlesDB(this);
initDB();
initialize();
}
public void initialize() {
this.getPickUpLine = (Button) findViewById(R.id.bGetLine);
this.getPickUpLine.setOnClickListener(this);
this.pickUpLine = (TextView) findViewById(R.id.tvLine);
this.pickUpLine.setOnClickListener(this);
}
public void initDB() {
titles.open();
if (!this.titles.isExist()) {
titles.createEntry("The I \n Have Cancer");
titles.createEntry("The Ocean");
}
titles.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGetLine:
titles.open();
Random rnd = new Random();
int index = rnd.nextInt(titles.getLength()) + 1;
pickUpLine.setText(titles.getTitleById(index));
titles.close();
break;
case R.id.tvLine:
if(!pickUpLine.getText().toString().equals(""))
{
Intent intent = new Intent(this, PickAppLine.class);
intent.putExtra("key", pickUpLine.getText().toString());
startActivity(intent);
}
break;
}
}
}
Here is what I tried :
package com.pickapp.pachu.pickapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Golan on 19/08/2014.
*/
public class MainScreenFragment extends Fragment implements OnClickListener{
private TitlesDB titles;
private Button getPickUpLine;
private TextView pickUpLine;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
titles = new TitlesDB(getActivity());
initDB();
View v = getView();
initialize(v);
return inflater.inflate(R.layout.activity_main_screen, container, false);
}
public void initialize(View v) {
this.getPickUpLine = (Button) v.findViewById(R.id.bGetLine);
this.getPickUpLine.setOnClickListener(this);
this.pickUpLine = (TextView) v.findViewById(R.id.tvLine);
this.pickUpLine.setOnClickListener(this);
}
public void initDB() {
titles.open();
if (!this.titles.isExist()) {
titles.createEntry("The I \n Have Cancer");
titles.createEntry("The Ocean");
}
titles.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGetLine:
titles.open();
Random rnd = new Random();
int index = rnd.nextInt(titles.getLength()) + 1;
pickUpLine.setText(titles.getTitleById(index));
titles.close();
break;
case R.id.tvLine:
if(!pickUpLine.getText().toString().equals(""))
{
Intent intent = new Intent(this, PickAppLine.class);
intent.putExtra("key", pickUpLine.getText().toString());
startActivity(intent);
}
break;
}
}
}
We won't just fix all your code. You have to do that yourself! Remove everything that you don't need at the beginning and start adding one after the other again. Fix all the errors on the way. It is hard to know what the actual problem is when everything is wrong.
One thing that I see right away that definitely does not work is this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main_screen, container, false); // NO, NO, NO!!
titles = new TitlesDB(getActivity());
initDB();
initialize();
}
You have a return statement in the method BEFORE you have more code. That can not work. The return statement has to be at the end!
I have created a MenuActivity which is having an Action Bar and an Split Action Bar. I want to use this actionbar and splitactionbar view for all activities in my application. I am a newbie to android so can somebody guide me stepwise about this.
Also I am trying to put the search icon on actionbar which is right now appearing on SplitActionBar. I have four icons on SplitActionBar and i want to show search icon on the actionbar not on the SplitActionBar. The search icon is a SearchView item which when clicked expands on ActionBar, which is very untidy. I want it to appear on rightmost position in the ActionBar and expand on the same when clicked.
This is MenuACtivity.java:
package com.example.travelplanner;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.example.travelplanner.R;
public class MenuActivity extends Activity implements OnItemClickListener{
Timer t1;
TimerTask tt1;
ImageView slide;
int currindex = 0;
ActionBar actionBar;
ArrayList<ItemDetails> image_details = GetSearchResults();
private int IMAGE_IDS[] = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3,R.drawable.slide4};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_menu);
final ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new MenuAdapter(this,image_details));
lv.setOnItemClickListener(this);
actionBar = getActionBar();
final Handler h = new Handler();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setIcon(R.drawable.ic_social_share);
LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.apptitle, null);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setCustomView(v);
int delay = 1000;
int period = 4000;
t1 = new Timer();
t1.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
h.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
animateSlideShow();
}
});
}
}, delay, period);
}
private void animateSlideShow(){
slide = (ImageView)findViewById(R.id.imagearr);
slide.setImageResource(IMAGE_IDS[currindex%IMAGE_IDS.length]);
currindex++;
Animation fade = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
slide.startAnimation(fade);
}
private ArrayList<ItemDetails> GetSearchResults(){
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
ItemDetails item_details = new ItemDetails();
item_details.setmenuitem("Featured Tours");
item_details.setItemDescription("Mostly Recommended");
item_details.setImageNumber(1);
results.add(item_details);
item_details = new ItemDetails();
item_details.setmenuitem("Theme Tours");
item_details.setItemDescription("Some amazing experiences");
item_details.setImageNumber(2);
results.add(item_details);
item_details = new ItemDetails();
item_details.setmenuitem("Holiday Packages");
item_details.setItemDescription("Bundles of happiness");
item_details.setImageNumber(3);
results.add(item_details);
item_details = new ItemDetails();
item_details.setmenuitem("Tailor Tours");
item_details.setItemDescription("Custommize your tours");
item_details.setImageNumber(4);
results.add(item_details);
item_details = new ItemDetails();
item_details.setmenuitem("Events");
item_details.setItemDescription("Experience the culture");
item_details.setImageNumber(5);
results.add(item_details);
item_details = new ItemDetails();
item_details.setmenuitem("Enquiry");
item_details.setItemDescription("Ask your queries");
item_details.setImageNumber(6);
results.add(item_details);
return results;
}
#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, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_action_search).getActionView();
return true;
}
#Override
public void onItemClick(AdapterView<?> av, View v, int position, long id) {
// TODO Auto-generated method stub
if(position==0){
Intent i0 = new Intent(this,FeaturedTourActivity.class);
startActivity(i0);
}
else if(position==1){
Intent i1 = new Intent(this,MainActivity.class);
startActivity(i1);
}
else if(position==2){
Intent i2 = new Intent(this,TourCatActivity.class);
startActivity(i2);
}
else if(position==3){
Intent i3 = new Intent(this,TailoredoneActivity.class);
startActivity(i3);
}
else if(position==4){
Intent i4 = new Intent(this,MainActivity.class);
startActivity(i4);
}
else if(position==5){
Intent i5 = new Intent(this,EnquireActivity.class);
startActivity(i5);
}
else if(position==6){
Intent i6 = new Intent(this,MainActivity.class);
startActivity(i6);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.menu_action_search:
{
Intent intent_search = new Intent(this,MainActivity.class);
startActivity(intent_search);
break;
}
case R.id.menu_action_locate:
{
Intent intent_nearby = new Intent(this,NearbyPlacesActivity.class);
startActivity(intent_nearby);
break;
}
case R.id.menu_action_mail:
{
Intent intent_mail = new Intent(this,EnquireActivity.class);
startActivity(intent_mail);
break;
}
case R.id.menu_action_call:
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9560875725"));
startActivity(callIntent);
break;
}
}
return super.onOptionsItemSelected(item);
}
}
Create BaseActivity which implements action bar.
And all your activities must inherit BaseActivity (not Activity)
public class BaseActiivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// action bar implementation
}
}
public class MainActivity extends BaseAcivity{
//your code
}
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();
}
}
}
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.