Button duplication in android when setting new text - android

I am working with the android support library, to be able to use fragments from Froyo, and the Sherlock extension, to show an ActionBar.
I have a fragment which shows three textViews and a button, and I want to be able to change the button text dinamically, depending on the content of the Intent. The problem is that when I call button.setText(String text), a second button appears. However, I've called button.getId() when clicking on each of them, and the Id is the same. I don't have a clue of why this is happening, so I'd appreciate some help.
The app is run on a Samsung Galaxy S, with Android 2.3.3. I can't upload a screen capture because I don't have enough reputation yet :(
This is the code:
FRAGMENT
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragment;
import com.parse.ParseUser;
import com.tiempoderodar.egdf.EGDF_App;
import com.tiempoderodar.egdf.R;
import com.tiempoderodar.egdf.security.Constants;
/**
* #author Daniel Leal López
*
*/
public class ChapterDetailsFragment extends SherlockFragment{
private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ChapterDetailsFragment", "Created");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ParseUser user = EGDF_App.getUser();
b = (Button) getSherlockActivity().findViewById(R.id.buttonWatchChapter);
if (user != null){
String chapterNumber = "";
Bundle extras = getSherlockActivity().getIntent().getExtras();
String s = extras.getString(Constants.CHAPTER_NUMBER_PARSE);
if((s != null)&&(!s.equals(""))){
// tvNumber.setText(s);
chapterNumber = "Chapter_" + s;
Log.i("Properties", s);
}
String seen = user.getString(chapterNumber);
if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_SEEN))){
b.setText("Second text: "+getString(R.string.watch_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to watch");
}
else if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_NOT_SEEN))){
b.setText("Second text: " + getString(R.string.buy_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to buy");
}else{
Log.w("DEV ERROR", "Chapter text not obtained");
}
}else{
Log.w("DEV ERROR", "ParseUser is null in EGDF_App!!!");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chapter_details, container, false);
return view;
}
public void setText(String item) {
getSherlockActivity().getSupportActionBar().setTitle(item);
}
public void setButtonText(String text){
b.setText(text);
}
}
Activity
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ChapterDetailsActivity extends SherlockFragmentActivity {
private Bundle extras;
MediaPlayer mMediaPlayer;
private String chapterNumber;
private boolean isChapterSeen;
// private int duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_details);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
ChapterDetailsFragment details = new ChapterDetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
Log.d("BUTTON PARENT VIEW", b.getParent().getClass().getName());
Log.d("BUTTON ID", String.valueOf(b.getId()));
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
String buyChapter = getString(R.string.buy_chapter_button_text);
}
#Override
protected void onPause() {
Log.i("Activity lifecycle", "On pause called");
super.onPause();
}
#Override
protected void onStop() {
Log.i("Activity lifecycle", "On stop called");
super.onStop();
}
#Override
protected void onDestroy() {
Log.i("Activity lifecycle", "On destroy called");
super.onDestroy();
EGDF_App.releaseMediaPlayer();
}
#Override
protected void onResume() {
Log.i("Activity lifecycle", "On resume called");
super.onResume();
}
#Override
protected void onStart() {
Log.i("Activity lifecycle", "On start called");
super.onStart();
}
}
Activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/chapterDetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.tiempoderodar.egdf.content.ChapterDetailsFragment" />
</LinearLayout>
Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewChapterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSeason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSinopsis"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterCredits"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<Button
android:id="#+id/buttonWatchChapter"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/watch_chapter_button_text"
android:layout_gravity="center"
android:onClick="watchChapter"/>
</LinearLayout>
Thanks!

I think I might have found the problem. I was calling
b = (Button) getSherlockActivity().findViewById(R.id.button);
but it should be
b = (Button) getView().findViewById(R.id.button);
With that change it works correctly

Related

change the text in another activity

I have a button in Activity A, which changes the text in it when clicked. There is an Activity B in which I need the TextView to become visible and its text to be the same as the text in the button on the Activity A. Please help.
Activity A
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class SmActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
View.OnClickListener appleListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
i = i;
}
}
};
View.OnClickListener cherryListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int j = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(j + 1));
j = j;
}
}
};
View.OnClickListener orangeListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_orange.setText("1");
}
else {
int k = Integer.parseInt(btn_orange.getText().toString());
btn_orange.setText(String.valueOf(k + 1));
k = k;
}
}
};
View.OnClickListener waterListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_waterLemon.setText("1");
} else {
int q = Integer.parseInt(btn_waterLemon.getText().toString());
btn_waterLemon.setText(String.valueOf(q + 1));
q = q;
}
}
};
btn_apple.setOnClickListener(appleListener);
btn_cherry.setOnClickListener(cherryListener);
btn_orange.setOnClickListener(orangeListener);
btn_waterLemon.setOnClickListener(waterListener);
}
public void OnClickBsk(View view){
Intent intent = new Intent(SmActivity.this, BasketActivity.class);
startActivity(intent);
}
public void OnClickProfile(View view){
Intent intent = new Intent(SmActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
Do this In Activity A when you click button to go to next Activity B
btn.setOnClickListener(v -> {
Intent i = new Intent(AActivity.this,BActivity.class);
// This below line sends Key- btnText and Value- Apple
i.putExtra("btnText","Apple");
startActivity(i);
});
In BActivity do this to button
// Here you receives data from activity a with the help of Key- btnText
btn.setText(getIntent().getStringExtra("btnText"));
This is a simple way to do this.
I Have Solved the answer for you,
Minor Explanations is in the comments in code.
Use this code as a concept and apply changes to yours based on your requirement.
XML of Activity A:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Before Button Click"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/text_to_change"
android:textSize="20sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_to_change"
android:id="#+id/change_text_btn"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Change Text and Start Activity B"
/>
</RelativeLayout>
Java of Activity A
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
TextView textView;
Button button;
textView=findViewById(R.id.text_to_change);
button=findViewById(R.id.change_text_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newtext="New Text From Activity A";
textView.setText(newtext);
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("Change", newtext);//this string will be
//accessed by activityB
startActivity(intent);
}
});
}
}
XML of Activity B:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting for New Text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/new_textview"
android:textSize="20sp"
android:visibility="gone"
/>
</RelativeLayout>
Java of Activity B:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
TextView textView;
textView=findViewById(R.id.new_textview);
// Below if block is looking for an intent, if it gets it and
// there is content in the extras with key "Change",
// it will make the textview in xml visible and update its string
// based on value set by Activity A
if(savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(ActivityB.this, "Can't Get the Intent", Toast.LENGTH_LONG).show();
} else {
String get_String = extras.getString("Change");
textView.setVisibility(View.VISIBLE);// be default i have set the visibility to gone in xml
//here it will get visible and then filled with the string sent by the intent in activity A
textView.setText(get_String);
}
}
}
}

How to pass data between fragments of a FragmentTabHost?

I'm trying to learn android and am having an issue with this project. I have set up a fragment tab host with four fragments. What I would like to do is have the first three fragments be interactive with the user and when they tab over to the 4th tab, it will display all the information they put in on the first three. I figured I can pass the info overriding on onPause() as the trigger as I don't want to use a button press. Right now, I'm just trying to get the EditText to work to make sure I'm doing everything right. I'm not sure if I'm using the fragment transaction correctly, or the way I'm trying to collect the edit text field. Later on I hope to pass the information via a bundle. Any help would be appreciated.
Main:
package valdes.fragmenttabsmenu;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements WelcomeFragment.WelcomeListener {
private FragmentTabHost mTabHost;
private String firstName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Home").setIndicator("Home", null), WelcomeFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Demographics").setIndicator("Demographics", null), DemographicsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Questions").setIndicator("Questions", null), QuestionsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Overview").setIndicator("Overview", null), OverviewFragment.class, null);
}
#Override
public void getFristName(String first_Name){
firstName = first_Name;
OverviewFragment fragment = new OverviewFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setFirstName(firstName);
ft.addToBackStack(null);
ft.commit();
}
}
Fragment 1 - getting info
package valdes.fragmenttabsmenu;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class WelcomeFragment extends Fragment {
public WelcomeFragment() {
// Required empty public constructor
}
interface WelcomeListener{
public void getFristName(String firstName);
}
private WelcomeListener listener;
private String firstName;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
EditText editText = (EditText) view.findViewById(R.id.first_name);
firstName = editText.getText().toString();
return view;
}
#Override
public void onAttach(Context context){
super.onAttach(context);
this.listener = (WelcomeListener)context;
}
#Override
public void onPause(){
super.onPause();
if(listener != null){
listener.getFristName(firstName);
}
}
}
Fragment 1 XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:text="#string/welcome_message"/>
<EditText
android:id="#+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/first_name"/>
<EditText
android:id="#+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/last_name"/>
<Spinner
android:id="#+id/birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/months"/>
</LinearLayout>
Fragment 2 - getting info
package valdes.fragmenttabsmenu;
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.TextView;
public class OverviewFragment extends Fragment {
private String firstName;
private String lastName;
public OverviewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_overview, container, false);
}
#Override
public void onStart(){
super.onStart();
View view = getView();
if(view != null){
TextView name = (TextView) view.findViewById(R.id.OV_name);
name.setText(firstName);
}
}
public void setFirstName(String firstName){this.firstName = firstName;}
}
Fragment 2 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="valdes.fragmenttabsmenu.OverviewFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:layout_weight="1"
android:text="#string/overview"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textSize="40sp"
android:text="Responses go here"/>
<TextView
android:id="#+id/OV_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="TEST"/>
<Button
android:id="#+id/submit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/submit"/>
</LinearLayout>
Create a Listner for get/set data between fragments and implement it on activity like this
InteractionLister.java
public interface InteractionLister {
void setData(String data);
String getData();
}
MainActivity.java
public class TabActivity extends Activity implements InteractionLister{
private String mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setData(String data) {
this.mData = data;
}
#Override
public String getData() {
return mData;
}
}
TabFragment1.java
public class TabFragment1 extends Fragment {
InteractionLister interactionLister;
private static final String TAG = TabFragment1.class.getSimpleName();
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.w(TAG,"Data from other fragment " + interactionLister.getData());
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
interactionLister = (InteractionLister) activity;
}
}

Android TextToSpeech doesn't work

I would like to use TTS in my application. First of all I'm trying to run some examples, but every time TTS doesn't work on my device. In example I have the code:
MainActivity:
package com.example.tts;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
private Button button;
private EditText inputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
inputText = (EditText) findViewById(R.id.inputText);
textToSpeech = new TextToSpeech(this, this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
convertTextToSpeech();
}
});
convertTextToSpeech();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
convertTextToSpeech();
}
} else {
Log.e("error", "Initilization Failed!");
}
}
#Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
private void convertTextToSpeech() {
//String text = "test";
String text = inputText.getText().toString();
if (null == text || "".equals(text)) {
text = "Please give some input.";
}
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextToSpeechActivity" >
<EditText
android:id="#+id/inputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="42dp"
android:layout_marginTop="28dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/inputText"
android:layout_below="#+id/inputText"
android:layout_marginTop="14dp"
android:text="Speak" />
</RelativeLayout>
After typing the word and clicking button application says nothing.
Does anyone have an idea how to solve it? Thanks in advance.

My Android ListFragment isn't displaying the list

The following ListFragment doesn't display anything other than a blank screen. I know the data are present. I'm not getting errors, just a blank (white) screen. I'm sure it's something silly. I'm fairly new to Android.
package com.pbs.deliverytrack1;
import com.pbs.deliverytrack1.DBContract;
import com.pbs.deliverytrack1.DBHelper;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OrderListFragment extends ListFragment {
SimpleCursorAdapter mAdapter;
String TAG = "OrderListFragment";
static final String[] PROJECTION = new String[] {
DBContract.DeliveryOrderTable._ID,
DBContract.DeliveryOrderTable.CUSTOMER,
DBContract.DeliveryOrderTable.ADDRESS };
// Selection criteria
static final String SELECTION = "(("
+ DBContract.DeliveryOrderTable.CUSTOMER + " NOTNULL) AND ("
+ DBContract.DeliveryOrderTable.CUSTOMER + " != '' ) AND ("
+ DBContract.DeliveryOrderTable.DELIVERED_DATETIME + " = '' ))";
private OnOrderSelectedListener listener = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String tag = TAG + ".onCreate()";
Log.d(tag,"Fragment created");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String tag = TAG + ".onCreateView()";
Log.d(tag, "Inflating fragment_order_list - or trying to.");
View view = inflater.inflate(R.layout.fragment_order_list, container,
false);
if (view == null) {
Log.d(tag, "Problem inflating view, returned null");
}
initializeList();
return view;
}
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
String tag = TAG + ".onActivityCreated()";
Log.d(tag,"Parent Activity Created");
}
public interface OnOrderSelectedListener {
public void onOrderSelected(long orderId);
// show detail record you dummy
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
String tag = "OrderListFragment.onAttach()";
Log.d(tag,"Attached!");
if (activity instanceof OnOrderSelectedListener) {
listener = (OnOrderSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
} // onAttach()
public void onStart() {
super.onStart();
Log.d(TAG + ".onStart()", "Started!!!");
}
public void onResume() {
super.onResume();
Log.d(TAG + "onResume()", "Resumed!!!");
}
public void onPause() {
super.onPause();
Log.d(TAG + ".onPause()", "Paused");
}
public void onStop() {
super.onStop();
Log.d(TAG + ".onStop()", "Stopped");
}
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG + ".onDestroyView()", "View Destroyed");
}
public void onDestroy() {
super.onDestroy();
Log.d(TAG + ".onDestroy()", "I'm dying!!!!");
}
public void onDetach() {
super.onDetach();
Log.d(TAG + ".onDetach()", "Off with the fragment!");
}
private void initializeList() {
String tag = TAG + ".initilizeList()";
Log.d(tag,"Setting up cursor.");
// for the cursor adapter, specify which columns go into which views
String[] fromColumns = {
DBContract.DeliveryOrderTable._ID,
DBContract.DeliveryOrderTable.CUSTOMER,
DBContract.DeliveryOrderTable.ADDRESS };
int[] toViews = {
R.id.list_view_order_id,
R.id.list_view_customer_field,
R.id.list_view_address_field };
// create an empty adapter we will use to display the loaded data.
DBHelper dbHelper = new DBHelper(getActivity());
Cursor cursor = dbHelper.getAllOrdersCursor();
if (cursor != null) {
cursor.moveToFirst();
Log.d(tag,"Creating SimpleCursorAdapter mAdapter");
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.fragment_order_list_row,
cursor,
fromColumns,
toViews,
0);
setListAdapter(mAdapter);
int count = mAdapter.getCount();
Log.d(tag, "Order Record Count = " + count);
if (mAdapter.isEmpty()) {
Log.d(tag, "Alas! mAdapter is empty");
} // end if mAdapter empty
} else { // cursor is null
Log.d(tag,"The cursor is null");
} // if cursor != null
}
}
This fragment is supposed to show a list derived from a SQLite query. The UI I'm building is a simple split list/detail screen on a tablet. I'm building for pre-Honeycomb, so I'm using the support library.
Let me know if you need to see any other parts of the code.
Here's fragment_order_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#00FF00"
android:drawSelectorOnTop="false" />
<TextView
android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="#string/err_no_data" />
</LinearLayout>
Here's the activity the ListFragment is called from:
package com.pbs.deliverytrack1;
import com.pbs.deliverytrack1.OrderListFragment.OnOrderSelectedListener;
import com.pbs.deliverytrack1.DBHelper;
import com.pbs.deliverytrack1.DeliveryOrder;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends FragmentActivity implements
OnOrderSelectedListener {
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String tag = TAG + ".onCreate()";
Log.d(tag, "Setting up database.");
new SetupDatabase().execute(this);
Log.d(tag, "Setting Content View");
setContentView(R.layout.activity_main);
}
#Override
public void onOrderSelected(long orderId) {
String tag = TAG + ".onOrderSelected()";
Log.d(tag,"Creating order detail fragment");
OrderDetailFragment fragment = (OrderDetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.detailFragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here's activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="horizontal"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/action_bar_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.pbs.deliverytrack1.MyActionBarFragment"
tools:layout="#layout/fragment_actionbar" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal"
>
<fragment
android:id="#+id/listFragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="40"
android:layout_gravity="bottom"
class="com.pbs.deliverytrack1.OrderListFragment" />
<fragment
android:id="#+id/detailFragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="60"
class="com.pbs.deliverytrack1.OrderDetailFragment"
tools:layout="#layout/fragment_order_detail" />
</LinearLayout>
</LinearLayout>
MainActivity's LinearLayout is set to:
android:orientation="horizontal"
But you seem to have a "vertical" design in mind, because your first child's width is "match_parent". This means that the ListView is drawn, just off the right side of the screen... Simply change the root layout's orientation.

codes in onClickListener can't be executed

I'm experiencing problem with the following code, I created two buttons with onClickListener added.
It works fine for the Button -- btnAbout, I'm trying to use another way to handle btnIntro, instead of by using findViewById(...) method, but the statement will not be executed when I click btnIntro.
Why does this happen?
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity {
private final String TAG = "tag";
private Button btnIntro;
private Button btnAbout;
private View layoutView;
private ViewWrapper wrapper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAbout = (Button) findViewById(R.id.btnAbout);
if (btnIntro == null) {
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
wrapper = new ViewWrapper(layoutView);
layoutView.setTag(wrapper);
} else {
wrapper = (ViewWrapper) layoutView.getTag();
}
btnIntro = wrapper.getButton();
Log.e(TAG, Integer.toHexString(layoutView.getId()) + "");
Log.e(TAG, btnIntro.getText().toString());
btnIntro.setOnClickListener(new OnClickListener() {
{
Log.e(TAG, "static");
}
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnIntro clicked");
Toast.makeText(TestActivity.this, "btnIntro", Toast.LENGTH_SHORT)
.show();
}
});
btnAbout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnAbout clicked");
Toast.makeText(TestActivity.this, "about", Toast.LENGTH_SHORT).show();
}
});
}
class ViewWrapper {
View base;
Button btn1;
ViewWrapper(View base) {
this.base = base;
}
Button getButton() {
if (btn1 == null) {
btn1 = (Button) base.findViewById(R.id.btnIntro);
Log.e(TAG, btn1.getText().toString());
}
return btn1;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MAIN_LAYOUT_XML"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="30dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Test" />
<Button
android:id="#+id/btnIntro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnIntro" />
<Button
android:id="#+id/btnAbout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnAbout" />
</LinearLayout>
Problem is that you use to different content views to obtain buttons, one is created when you invoke setContentView() and second you create by invoking inflator.infate(). Thus buttons you get are placed in different content views (only one of which is shown - that created by setContentView). Try that instead:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
setContentView(layoutView);
//..anything you need..
}

Categories

Resources