Android Handler Message and ListView - android

Here's my error:
*** Uncaught remote exception! (Exceptions are not yet supported across processes.)
android.util.AndroidRuntimeException: { what=1008 when=368280372 } This message is already in use.
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:171)
at android.os.Handler.sendMessageAtTime(Handler.java:457)
at android.os.Handler.sendMessageDelayed(Handler.java:430)
at android.os.Handler.sendMessage(Handler.java:367)
at android.view.ViewRoot.dispatchAppVisibility(ViewRoot.java:2748)
What I'm attempting is to have a listview, that is populated by custom list items, each list item has multiple views and each view has an onclick listener attached. When this onClickListener is pressed it sends a Message to a Handler with a what and arg1 arguments.
Clicking one of my elements fires an intent to start a new activity.
Clicking the other shows a toast.
When these are pressed in a combination I get the error above. Namely clicking the text to fire the intent, (then press back) then clicking the image to show the toast, then when you click the text to fire the intent again I get the FC.
And here is the code below, I tried to remove as much cruft as I could to get to the bones of the error:
If you want to skip to whats important look at the onClickListener's in ConversationAdapter.class and how they interact with StartPage.class
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.handler.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".StartPage"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailsPage"
android:label="DetailsPage"
>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
StartPage.class:
package com.handler.test;
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class StartPage extends ListActivity {
private ArrayList<Conversation> mConversations = null;
private ConversationAdapter mAdapter;
private Context mContext;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
mConversations = new ArrayList<Conversation>();
this.mAdapter = new ConversationAdapter(mContext, R.layout.inbox_row, mConversations, mHandler);
setListAdapter(this.mAdapter);
new Thread(new Runnable() {
#Override
public void run() {
getConversations();
}
}).start();
mProgressDialog = ProgressDialog.show(StartPage.this, "Please wait...", "Retrieving data ...", true);
}
private void getConversations() {
try {
mConversations = new ArrayList<Conversation>();
Conversation o1 = new Conversation();
o1.setStatus("SF services");
o1.setMessage("Pending");
mConversations.add(o1);
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(mConversations != null && mConversations.size() > 0){
mAdapter.notifyDataSetChanged();
for(int i=0;i<mConversations.size();i++)
mAdapter.add(mConversations.get(i));
}
mProgressDialog.dismiss();
mAdapter.notifyDataSetChanged();
}
};
private Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
int convIndex = msg.arg1;
int viewTouched = msg.what;
switch(viewTouched){
case ConversationAdapter.PROF_ICON:
showNumber(convIndex);
break;
case ConversationAdapter.MESSAGE:
showMessageDetails(convIndex);
break;
}
super.handleMessage(msg);
}
};
private void showNumber(int convIndex) {
Toast.makeText(mContext, "Pressed: "+convIndex, Toast.LENGTH_LONG).show();
}
private void showMessageDetails(int convIndex) {
final Conversation conv = mConversations.get(convIndex);
Intent i = new Intent(mContext, DetailsPage.class);
i.putExtra("someExtra", conv);
startActivity(i);
}
}
DetailsPage.class
package com.handler.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class DetailsPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Test", "Details Page");
}
}
Conversation.class:
package com.handler.test;
import java.io.Serializable;
public class Conversation implements Serializable {
private static final long serialVersionUID = -437261671361122258L;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ConversationAdapter.class:
package com.handler.test;
import java.util.ArrayList;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ConversationAdapter extends ArrayAdapter<Conversation> {
public static final int PROF_ICON = 0;
public static final int MESSAGE = 1;
private Context mContext;
private Handler mHandler;
private ArrayList<Conversation> mItems;
private int mXmlId;
private LinearLayout detailsOfConv;
private ImageView iconImage;
public ConversationAdapter(Context context, int textViewResourceId, ArrayList<Conversation> items, Handler handler) {
super(context, textViewResourceId, items);
this.mContext = context;
this.mItems = items;
this.mXmlId = textViewResourceId;
this.mHandler = handler;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mXmlId, null);
}
final Message m = new Message();
m.arg1 = position;
Conversation c = mItems.get(position);
if (c != null) {
iconImage = (ImageView) v.findViewById(R.id.icon);
if (iconImage != null) {
iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = PROF_ICON;
mHandler.sendMessage(m);
}
});
}
detailsOfConv = (LinearLayout) v.findViewById(R.id.details);
if(detailsOfConv != null){
detailsOfConv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = MESSAGE;
mHandler.sendMessage(m);
}
});
}
}
return v;
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
>
<ListView
android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
/>
</LinearLayout>
inbox_row.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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:src="#drawable/icon" />
<LinearLayout
android:id="#+id/details"
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/toptext"
android:textColor="#99FF66"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:text="123456789"
/>
</LinearLayout>
</LinearLayout>

My guess would be that you are sending twice the same message. Indeed in the code there is one new Message() and two mHandler.sendMessage(m) which are possibly both executed.
Try making a new message for every time you send a message.
Edited:
Message.obtain() is preferable to Message m = new Message() (because it recycles used messages under the hood)
In your case you could use new.copyFrom(old) if you need a copy of existing message.

Related

having trouble with TabLayout using fragments and JSON

Hi I been trying for a while to figure this out and checked a lot of post. I am having this problem when I switch to a new tab only the XML layout is showing. Though when I start on the first tab and fragment the json content shows up how I like. I am not sure how to get the json content to change for a new tab.
Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class TVFragment extends Fragment {
public TVFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tv_activity, container, false);
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
this.loadMovieInfo(media);
// loadMoviePoster(media);
return rootView;
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}
MainActivity
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Samuel on 2/12/2018.
*/
public class TechnologyResultsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the tv_activitylayout file
setContentView(R.layout.tab_viewpager_activity);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
MediaTypeAdapter adapter = new MediaTypeAdapter(getSupportFragmentManager(),getApplicationContext());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
Adapter
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Samuel on 2/14/2018.
*/
public class MediaTypeAdapter extends FragmentPagerAdapter {
public MediaTypeAdapter(FragmentManager fragmentManager, Context applicationContext){
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TVFragment();
} else if (position == 1) {
return new MovieFragment();
}
else {
return new MovieFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "TV";
} else {
return "MOVIES";
}
}
}
tablayout
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
movie_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="wrap_content"
android:orientation="horizontal"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/poster"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:src="#drawable/poster"
android:layout_weight="1"
/>
<ScrollView
android:id="#+id/synopsis_scroll"
android:layout_width="match_parent"
android:layout_height="81dp"
android:padding="8dp">
<TextView
android:id="#+id/synopsis_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Academy Award nominee, heart-warming, hit comedy from producer Judd Apatow (Bridesmaids and Trainwreck). The Big Sick is based on the real-life courtship between Pakistan-born comedian Kumail Nanjiani (Nanjiani) and grad student Emily Gordon (Zoe Kazan) who fall in love but struggle while dealing with Emily's mysterious illness and their families culture clash. Also staring Ray Romano and Holly Hunter. Included with Prime."/>
</ScrollView>
</LinearLayout>
</LinearLayout>
you have to create a new class moviefragment and have to write code to fetch movies in that.
public class MovieFragment extends Fragment{
TechnologyResultsActivity technology;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
technology= (TechnologyResultsActivity) context;
}
public static Fragment newInstance(Bundle bundle){
MovieFragment movie=new MovieFragment();
if(bundle!=null){
movie.setArguments(bundle);
}
return movie;
}
#Override
public void onResume() {
super.onResume();
// this will only called when fragment is visible to user
if(isVisible()) {
if (Constant.isInternetConnected(homeActivity)) {
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
loadMovieInfo(media)
} else {
Toast.makeText(homeActivity, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}

Android SharedPreferences not removed until app is restarted

I'm stucked with this problem.
In my app I use SharedPrefManager as a singleton class, in order to keep some "session" information. In this simple example app I just save the user's name and a boolean that indicates whether or not the user is logged in to skip the login screen if already logged, or to show it if not.
When starting the app, after the splashscreen, the LoginActivity is started.
At this point, if the user has already logged in before (without logging out later, that means the boolean value of isuseradded SharedPreferences variable is true), the user is redirected to the MainActivity, otherwise he sees the login form, where he can insert username and password and make a REST API request to a remote server.
If the login is correct, the MainActivity starts and simply shows the name of the user, taken from the response JSON obtained by the remote login REST API call.
Now, here is my problem: I want to implement a simple logout feature that deletes (or changes, as in this test app) all the information stored by SharedPreferences and takes the user back to the LoginActivity.
But when I click logout, the values for SharedPreferences are updated only in MainActivity, while in LoginActivity they remain the same as before, so when the user is redirected to LoginActivity, the isusedadded shared preference is still true, and the user is redirected back to MainActivity.
But SharedPrefManager class is a singleton, so its values should be the same in every part of the app, because only one instance of it exists, so why do I have this behavior?
You can test the app by downloading the full app code here and using these credentials for login:
Username: 52346
Password: 32fjueM1 (case sensitive)
Here follows my code.
App.java:
package mypackage.sharedprefapp;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class App extends Application
{
private RequestQueue mRequestQueue;
private static App mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized App getInstance()
{
return mInstance;
}
// This method returns the queue containing GET/POST requests
public RequestQueue getRequestQueue()
{
if(mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
// This method adds a GET/POST request to the queue of requests
public <T> void addToRequestQueue(Request<T> req)
{
getRequestQueue().add(req);
}
}
SplashActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
LoginActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity
{
private static final String TAG = "LoginActivity";
Button loginButton;
EditText userIDInput, passwordInput;
TextView loginErrorMsg, title;
LinearLayout bgLayout;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onCreate: "+sharedPrefManager.isUserAdded());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onResume: "+sharedPrefManager.getUserName());
// if the user is already logged in
if(sharedPrefManager.isUserAdded())
{
Log.i(TAG, "User is logged in");
// if the device is connected to the internet
if(Utils.isDeviceOnline(this))
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// if the device is offline
else
{
Log.i(TAG, "Internet connection is not available");
}
}
// if the user is not logged in
else
{
Log.i(TAG, "User is NOT logged in");
setContentView(R.layout.activity_login);
title = (TextView) findViewById(R.id.title);
loginErrorMsg = (TextView) findViewById(R.id.login_errorText);
userIDInput = (EditText) findViewById(R.id.login_id_paziente);
passwordInput = (EditText) findViewById(R.id.login_password);
loginButton = (Button) findViewById(R.id.login_submitButton);
bgLayout = (LinearLayout) findViewById(R.id.login_parentLayout);
// Bind a custom click listener to the login button
loginButton.setOnClickListener(new LoginButtonClickListener(this));
// Bind a custom click listener to the background layout
// so that the soft keyboard is dismissed when clicking on the background
bgLayout.setOnClickListener(new LoginBackgroundClickListener());
}
}
}
LoginButtonClickListener.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginButtonClickListener implements View.OnClickListener
{
private Context context;
private SharedPrefManager sharedPrefManager;
public LoginButtonClickListener(Context c)
{
this.context = c;
}
#Override
public void onClick(View v)
{
sharedPrefManager = SharedPrefManager.getInstance(context);
// if internet connection is available
if(Utils.isDeviceOnline(context))
{
// Verify login credentials from DB
doLogin();
}
else {}
}
// check login data with REST API
private void doLogin()
{
final String paziente_id = ((EditText)((Activity)context).findViewById(R.id.login_id_paziente)).getText().toString();
final String paziente_password = ((EditText)((Activity)context).findViewById(R.id.login_password)).getText().toString();
StringRequest stringRequest = new StringRequest
(
Request.Method.POST,
"http://www.stefanopace.net/iCAREServer/api/v1/index.php/login",
new Response.Listener<String>()
{
#Override
public void onResponse(String s)
{
try
{
JSONObject obj = new JSONObject(s);
if(!obj.getBoolean("error"))
{
String name = obj.getString("nome");
sharedPrefManager.addUser(name);
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
else
{
Toast.makeText(context, "Error on JSON response", Toast.LENGTH_LONG).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError volleyError)
{
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id_paziente", paziente_id);
params.put("password", paziente_password);
return params;
}
};
App.getInstance().addToRequestQueue(stringRequest);
}
}
LoginBackgroundClickListener.java
package mypackage.sharedprefapp;
import android.view.View;
public class LoginBackgroundClickListener implements View.OnClickListener
{
#Override
public void onClick(View v)
{
Utils.hideSoftKeyboard(v);
}
}
MainActivity.java
package mypackage.sharedprefapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
TextView personName;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
setContentView(R.layout.activity_main);
personName = (TextView) findViewById(R.id.person_name);
Log.i(TAG, "Value: "+sharedPrefManager.isUserAdded());
personName.setText(sharedPrefManager.getUserName());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.w("MainActivity", "onResume");
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
// Logout button has been pressed
case R.id.logout_action:
{
Log.i("Logout pressed", "Logout button has been pressed!");
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton
(
"Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
boolean success = sharedPrefManager.removeDataFromSharedPreference();
// if the operation is OK
if(success)
{
// go to the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Error during logout", Toast.LENGTH_LONG).show();
}
}
}
);
alertDialogBuilder.setNegativeButton
(
"No",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
SharedPrefManager.java
package mypackage.sharedprefapp;
import android.content.Context;
import android.content.SharedPreferences;
public final class SharedPrefManager
{
private static final String TAG = "SharedPrefManager";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static SharedPrefManager mInstance;
private static final String SHARED_PREF = "sharedprefs";
private static final String KEY_IS_USER_ADDED = "isuseradded";
public static final String KEY_USER_NAME = "username";
private SharedPrefManager(Context context)
{
sharedPreferences = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
sharedPreferences.registerOnSharedPreferenceChangeListener(new LocalSharedPreferencesChangeListener());
}
public static SharedPrefManager getInstance(Context context)
{
if(mInstance == null)
{
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
// add an user to the shared preferences
public boolean addUser(String name)
{
editor.putString(KEY_USER_NAME, name);
editor.putBoolean(KEY_IS_USER_ADDED, true);
return editor.commit();
}
public boolean removeDataFromSharedPreference()
{
editor.putString(KEY_USER_NAME, "HELLO");
editor.putBoolean(KEY_IS_USER_ADDED, false);
return editor.commit();
}
public String getUserName()
{
return sharedPreferences.getString(KEY_USER_NAME, "");
}
public boolean isUserAdded()
{
return sharedPreferences.getBoolean(KEY_IS_USER_ADDED, false);
}
}
Utils.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class Utils
{
public static void hideSoftKeyboard(View view)
{
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// This method checks if the device is connected to the Internet
public static boolean isDeviceOnline(final Context context)
{
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null)
{
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isOnline = (networkInfo != null && networkInfo.isConnectedOrConnecting());
if(!isOnline)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setCancelable(false);
alertDialog.setTitle("Error");
alertDialog.setMessage("Internet is not available");
alertDialog.setPositiveButton("Try again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Reload the Activity
Intent intent = ((Activity) context).getIntent();
((Activity) context).finish();
context.startActivity(intent);
}
});
alertDialog.show();
}
return isOnline;
}
return false;
}
}
LocalSharedPreferencesChangeListener
package mypackage.sharedprefapp;
import android.content.SharedPreferences;
import android.util.Log;
public class LocalSharedPreferencesChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.i("HERE", key);
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginActivity"
android:padding="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+id/login_parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:singleLine="false"
android:padding="5dp"
android:textSize="30sp" />
<EditText
android:id="#+id/login_id_paziente"
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="number"
android:ems="10"
android:hint="Username"
android:textColor="#android:color/black"
android:textColorHint="#android:color/darker_gray"
android:singleLine="true"
android:minLines="1"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Password"
android:textColorHint="#android:color/darker_gray"
android:inputType="textPassword"
android:ems="10"
android:textColor="#android:color/black"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<TextView
android:id="#+id/login_errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login error"
android:textColor="#android:color/holo_red_dark"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:singleLine="false"
android:padding="5dp"
android:textSize="20sp"
android:layout_margin="10dp"
android:visibility="invisible" />
<Button
android:id="#+id/login_submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="20sp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
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="mypackage.sharedprefapp.MainActivity">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
splashscreen.xml (in drawable resources folder)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark"/>
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
mainmenu.xml (in res/menu resource folder)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/logout_action"
android:title="Logout"
app:showAsAction="always" />
</menu>
styles.xml
<resources>
...
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/splashscreen</item>
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mypackage.sharedprefapp">
<!-- Needs internet to connect to Google Services -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission to check internet connection state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" />
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:process=":other_process"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.LOGIN_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle (Module: app)
dependencies {
...
compile 'com.android.volley:volley:1.0.0'
}
Thank you!
Just call editor.clear();
and editor.commit();
is enough to delete all data from shared preference.
Because onResume, you keep on instantiating a new SharedPrefManager
sharedPrefManager = new SharedPrefManager(this);
Modify your SharedPrefManager so that it only gives one instance at all times OR make sure that you are referring to the same object when you return to LoginActivity.
SharedPreferences is permanent storage, you can clear
SharedPreferences.Editor.clear().commit();
alternate solution
you want once app close clear entire values,try Application singleton class
#Ciammarica you can call this code on click of Logout button, hope this can help you..you can set in logout button boolean value false..
SessionManager.setUserLoggedIn(YourActivity.this, false); SessionManager.clearAppCredential(YourActivity.this);
I Changed my code in order to have only one instance of SharedPrefManager class.
This is my App singleton class:
public class App extends Application
{
private static App mInstance;
private SharedPrefManager sharedPrefManager;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
sharedPrefManager = new SharedPrefManager(this);
}
public SharedPrefManager getSharedPrefManager(){
return sharedPrefManager;
}
public static synchronized App getInstance(){
return mInstance;
}
}
Then from other classes I get the instance by calling
SharedPrefManager sharedPrefManager = App.getInstance().getSharedPrefManager();
Now, with this change, the onSharedPreferenceChanged() event is triggered only once, so this is better than before, but the "delayed" behavior is still there... I mean, even if I use editor.clear(); and editor.commit(); methods, the values are updated but I can see them only if I close and open the app again.
I found the problem myself... It didn't like the sharedPrefManager.removeDataFromSharedPreference(); method to be called from inside new DialogInterface.OnClickListener()
I took it in another part of the code and it worked.

changing activity on android

I've difficult with changing activity on android.
I started my app(display main.xml) and clicked Start button(display listening.xml).
When I had pressed back button, background disappeared on my app.
[display main.xml]
[display listening.xml]
detecting display.. (A image not attached because I have less reputation :( )
[display main.xml (Problem)]
Following is my source code.
(Some code are omitted.)
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
LayoutInflater inflater = LayoutInflater.from(this);
mainView = inflater.inflate(R.layout.main, null);
listeningView = inflater.inflate(R.layout.listening, null);
setContentView(mainView);
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start Button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe Button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
setContentView(listeningView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "종료");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) { // Start Button
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02) // ReadMe Button
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
// omitted..
}
Please give me some advice.
Sorry for my bad english.
Thanks in advance.
Following are added context.
I tried to change inflater to setContentView().
But, It's not worked.
I clicked start button and touched back key on my phone.
My phone said "Unfortunately, (MY_APP_NAME) has stopped."
I reupload my source code.
[MainActivity.java]
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
// LayoutInflater inflater = LayoutInflater.from(this); // disable inflater
setContentView(R.layout.main);
// mainView = inflater.inflate(R.layout.main, null); // disable inflater
// listeningView = inflater.inflate(R.layout.listening, null); // disable inflater
// setContentView(mainView); // disable inflater
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
//setContentView(listeningView);
setContentView(R.layout.listening);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Exit");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
NotificationManager notiMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notiMgr.cancel(999); // Notification의 고유 id가 999인 것을 찾아서 notification을 종료한다.
finish();
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) {
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02)
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
private void Threadsleep(DetectorThread detectorThread){
try
{
detectorThread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onWhistleDetected() {
runOnUiThread(new Runnable() {
public void run() {
TextView textView = (TextView)
MainActivity.mainApp.findViewById(R.id.detectedNumberText);
textView.setText(String.valueOf(numWhistleDetected++));
if (numWhistleDetected > 1) {
setEvent();
}
}
});
Threadsleep(detectorThread);
}
}
[main.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/car">
<Button
android:id="#+id/whistleButton"
android:layout_width="150dp"
android:layout_height="40dp"
android:gravity="center"
android:text="Start"
android:textSize="20dp"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
<Button
android:id="#+id/whistleButton02"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_below="#id/whistleButton"
android:gravity="center"
android:text="ReadMe"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:textSize="20dp"
android:layout_marginTop="15dp"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
</RelativeLayout>
[listening.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background ="#drawable/worker"
>
<TextView
android:id="#+id/listening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:textSize="30dp"
android:text="Detecting.." />
<TextView
android:id="#+id/detectedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:layout_centerInParent="true"
android:textSize="20dp" />
<TextView
android:id="#+id/detectedNumberText"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:textSize="5dp"
android:layout_toRightOf="#+id/detectedText"
/>
</RelativeLayout>
[help.xml]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="112dp"
android:layout_marginTop="20dp"
android:text="Read Me...." />
</RelativeLayout>
[AndroidManifest.xml]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.musicg.demo.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="#drawable/ear"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".listening"></activity>
<activity android:name="help"></activity>
</application>
</manifest>
First of all Use setContentView(R.layout.main) in onCreate() in your oncreate as Akhil mentioned instead of inflating.
Also to set background image to your activity use android:background="#drawable/image_name" to your root container in main.xml.
If you are trying to dynamically switch the image in your lisenter.
Try and let us know if it worked.
Also to get more understanding can to show contents of your main.xml ?

Android change tab without losing data

I'm working with tabs in android, according to my requirement I need to open a popup containing 5 tabs. That is, I have a Fragment where I have to open a DialogFragment and this DialogFragment need to show my 5 tabs. So far so quiet! Could enter each content on their respective tabs.
But the problem is that when I change the tab, the values ​​that were entered in another tab are clean. example:
I go into tab1 fills any value in a text field and then when I switch to tab2 tab1 back to the value it had before entered is lost.
Given this scenario, how do I retain the values ​​that were filled to the brim change? Follow the code below to explain further.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import br.com.company.R;
import br.com.company.beans.Ordem;
import br.com.company.dispatcher.IDispacher;
import br.com.company.fragment.helper.IFragmentCo;
import br.com.company.bo.IClasseBO;
public class TabsFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private Spinner classe;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public TabsFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TabsFragment.this.dismiss();
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(newTab(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, R.ordem_encerramento.dados_cliente));
mTabHost.addTab(newTab(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, R.ordem_encerramento.defeito_falha));
mTabHost.addTab(newTab(TAB_SERVICOS, R.string.tab_servico, R.ordem_encerramento.servico));
mTabHost.addTab(newTab(TAB_MATERIAIS, R.string.tab_material, R.ordem_encerramento.material));
mTabHost.addTab(newTab(TAB_OBSERVACAO, R.string.tab_observacao, R.ordem_encerramento.observacao));
}
private View addView(int resource) {
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(resource, null);
return view;
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View view = LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(view);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
View view = null;
if (TAB_DADOS_CLIENTE.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
mTabHost.setCurrentTab(0);
} else if (TAB_DEFEITO_FALHA.equals(tabId)) {
view = new DefeitoFalhaView().createView(getActivity());
mTabHost.getTabContentView().addView(view);
mTabHost.setCurrentTab(1);
} else if (TAB_SERVICOS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.servico));
mCurrentTab = 2;
} else if (TAB_MATERIAIS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.materiais));
mCurrentTab = 3;
} else if (TAB_OBSERVACAO.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.observacao));
mCurrentTab = 4;
}
}
public View getmRoot() {
return mRoot;
}
}
File 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:background="#color/White"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="30dip"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:paddingRight="10dip" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:text="Devolver OS"
android:textColor="#color/Black" />
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+ordem_encerramento/cancelar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Cancelar" />
<Button
android:id="#+ordem_encerramento/enviar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Enviar" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#xml/menu_bg" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EFEFEF" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+ordem_encerramento/dados_cliente"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/defeito_falha"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/servico"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/material"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/observacao"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
</ScrollView>
</LinearLayout>
Try storing those values somewhere e.g.SharedPreferences or static variable and setting them back in onTabChanged().
TabGroupActivity.java
import java.util.ArrayList;
import com.data.DataClass;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
/**
* The purpose of this Activity is to manage the activities in a tab. Note:
* Child Activities can handle Key Presses before they are seen here.
*
* #author Eric Harlow
*/
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
// onBackPressed();//Added after
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
if (DataClass.isTemp()) {
overridePendingTransition(R.anim.slide_in_up,
R.anim.slide_in_up);
}
current.finish();
}
}
}
MainTab.java
import com.data.DataClass;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.LinearLayout.LayoutParams;
public class MainTabInfoMe extends TabActivity {
public final static int HOME = 1;
public final static int DIARY = 2;
public final static int PROGRESS = 3;
long transactionID = -1;
public static TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mytabs);
MyView view = null;
tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, TabGroup1Activity.class);
view = new MyView(this, R.drawable.home_select, R.drawable.home, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Home").setIndicator(view).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup2Activity.class);
view = new MyView(this, R.drawable.prof_select, R.drawable.prof, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Diary").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup3Activity.class);
view = new MyView(this, R.drawable.bus_select, R.drawable.bus, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("progress").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(1).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
if (MyApplication.getFrom().equals("Home")) {
tabHost.setCurrentTab(0);
} else if (MyApplication.getFrom().equals("Diary")) {
tabHost.setCurrentTab(1);
} else if (MyApplication.getFrom().equals("progress")) {
tabHost.setCurrentTab(2);
}
int type = 0;
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("from")) {
type = getIntent().getExtras().getInt("from");
switch (type) {
case HOME:
tabHost.setCurrentTab(0);
case DIARY:
tabHost.setCurrentTab(1);
case PROGRESS:
tabHost.setCurrentTab(2);
default:
tabHost.setCurrentTab(0);
}
}
}
}
public long getTransactionID() {
return transactionID;
}
public void setTransactionID(long l) {
transactionID = l;
}
public void switchTabSpecial(int tab) {
tabHost.setCurrentTab(tab);
}
class ChangeTabReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tabHost = getTabHost();
tabHost.setCurrentTab(1);
}
}
private class MyView extends LinearLayout {
ImageView iv;
public MyView(Context c, int drawable, int drawableselec, String label) {
super(c);
iv = new ImageView(c);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(SELECTED_STATE_SET, this.getResources()
.getDrawable(drawable));
listDrawable.addState(ENABLED_STATE_SET, this.getResources()
.getDrawable(drawableselec));
iv.setImageDrawable(listDrawable);
iv.setBackgroundColor(Color.TRANSPARENT);
iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, (float) 0.0));
iv.setPadding(0, 0, 0, 5);
setGravity(Gravity.CENTER);
addView(iv);
}
}
#Override
protected void onPause() {
super.onPause();
if( DataClass.isTemp()){
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_in_up);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
FirstTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
SecondTab of class
public class TabGroup2Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
thirdTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
static variable class
import android.app.Application;
public class MyApplication extends Application {
private static String from = "Home";
public static String getFrom() {
return from;
}
public static void setFrom(String fromPage) {
from = fromPage;
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TabHost android:id="#android:id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TabWidget android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/topbarbck"/>
</RelativeLayout>
</TabHost>
</LinearLayout>
put all file and check it
Thanks to all who tried to help me!
I do not have much experience with android but from what I saw, the classes must be executed according to the hierarchy proposed by android. That is, in my case I have a main activity which calls the mine fragments and through one of the fragments I had to call a DialogFragment and this would inflate DialogFragment several Views (my tabs), so I have the following structure:
Activity > Fragment > DialogFragment > Views
Based on this solution for my case was thus:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class OrdemEncerramentoFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public OrdemEncerramentoFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
OrdemEncerramentoFragment.this.dismiss();
}
});
enviar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = mTabHost.getChildAt(0);
new DefeitoFalhaView().getDadosDefeitoFalha(view);
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(0);
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(inserirAba(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, new DadosClienteView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, new DefeitoFalhaView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_SERVICOS, R.string.tab_servico, new ServicoView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_MATERIAIS, R.string.tab_material, new MaterialView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_OBSERVACAO, R.string.tab_observacao, new ObservacaoView().createView(getActivity())));
}
private TabSpec inserirAba(String tag, int labelId, final View view) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return(view);
}
});
spec.setIndicator(buildTabIndicator(labelId));
return spec;
}
private View buildTabIndicator(int msg) {
View indicator=LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv=(TextView)indicator.findViewById(R.id.tabsText);
tv.setText(msg);
return(indicator);
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
}
public View getmRoot() {
return mRoot;
}
}

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