Android TextView troubles - java

Ok so i'm starting to learn Android and i cant append or set the text of the TextView.. i always get a NullPointerException.. anyone help me out?
Field variables
public TextView t = null;
public Button b = null;
My onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
t = (TextView)findViewById(R.id.textView1);
b = (Button)findViewById(R.id.dummy_button);
//t.append("hello again");
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
The listener i decided to put the append in..
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("onClick", "before append");
t.append("ummmm" + System.currentTimeMillis());
Log.e("onClick", "after");
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
Here is the .xml file that i use in layout
<FrameLayout 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:background="#0099cc"
tools:context=".FullscreenActivity" >
<!--
The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc.
-->
<TextView
android:id="#+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:text="#string/dummy_content"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<Button
android:id="#+id/dummy_button"
style="?buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/dummy_button" />
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="411dp"
android:text="Why Hello There" />
</FrameLayout>
R.java.. it is auto generated however.. here is inside R.java
public static final class id {
public static final int dummy_button=0x7f070002;
public static final int fullscreen_content=0x7f070000;
public static final int fullscreen_content_controls=0x7f070001;
public static final int textView1=0x7f070003;
}
Any help would be amazing! :) i am quite new to Android development

You are missing setContentView(R.layout.your_layout_id);
Add it after super.onCreate and before you are finding any views.

Your OnCreate should be like this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml);
t = (TextView)findViewById(R.id.textView1);
b = (Button)findViewById(R.id.dummy_button);
}

It seems that you forget to call setContentView method

Related

Onclick listener not responding to clicks on imageview

I have a problem on getting my imageview button to work onclick. what im trying to do is to make the first image invisible so that the second one behind it can appear and at the same time define int special based on what image that has been clicked.
public class TrainingActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageView a12,b13,a12a,b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
////////////////////////////////////////////////////////////////////////
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
a12 = (ImageView) findViewById(R.id.young);
b13 = (ImageView) findViewById(R.id.old);
a12a = (ImageView) findViewById(R.id.young2);
b13a = (ImageView) findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special =0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special =1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
this is my main class file. I've had already tried this codes in a new project and it works there but somehow doesn't here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/gray_color"
tools:context="com.codestudioapps.cardioexcercise.WalkandStep.activities.TrainingActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/young2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area1"
/>
<ImageButton
android:id="#+id/young"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area" />
<ImageButton
android:id="#+id/old2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat1"
/>
<ImageButton
android:id="#+id/old"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And this is the layout. The problem might happen because of my manifest file but im unsure. Does anyone have any ideas?
Your code seems okay. Just, casting problem i.e. ImageButton to ImageView.
Your code should be as follows:
public class DemoActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageButton a12, b13, a12a, b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
a12 = findViewById(R.id.young);
b13 = findViewById(R.id.old);
a12a = findViewById(R.id.young2);
b13a = findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special = 0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special = 1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
}

Common Progress bar in every activity Android

I have modify the solution. I am able to get the progress bar but the progress bar never gets hide
Here is class to create a progress bar with relative layout
public class ProgressBarHandler {
private ProgressBar mProgressBar;
private Context mContext;
private View _baseView;
private View _hideView;
public ProgressBarHandler(Context context,View baseView, View hideView) {
mContext = context;
_baseView = baseView;
_hideView = hideView;
ViewGroup layout = (ViewGroup) _baseView;//((Activity) context).findViewById(android.R.id.content).getRootView();
mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
mProgressBar.setIndeterminate(true);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
RelativeLayout rl = new RelativeLayout(context);
rl.setGravity(Gravity.CENTER);
rl.addView(mProgressBar);
layout.addView(rl, params);
hide();
}
public void show() {
mProgressBar.setVisibility(View.VISIBLE);
_hideView.setVisibility(View.INVISIBLE);
}
public void hide() {
mProgressBar.setVisibility(View.INVISIBLE);
_hideView.setVisibility(View.VISIBLE);
}
}
This is my xml file
<FrameLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:id="#+id/profile_activity">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/layout_to_hide"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleTextAppearance="#android:color/transparent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#mipmap/wallpaper"
android:orientation="vertical">
<com.deerwalk.androidcommon.RoundedImageView
android:id="#+id/profile_image"
android:layout_width="100dp"
app:civ_border_color="#EEEEEE"
app:civ_border_width="4dp"
app:civ_shadow="true"
app:civ_shadow_radius="10"
app:civ_shadow_color="#8BC34A"
android:layout_height="100dp"
android:layout_alignWithParentIfMissing="false"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_margin="20dp"
android:src="#drawable/avatar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/profile_image"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/txt_name"
android:layout_gravity="center_horizontal"
android:text=""
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/txt_dob"
android:layout_gravity="center_horizontal"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#color/white" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
Here is the activity class which call the progress bar
public class ProfileActivity extends AppCompatActivity {
FrameLayout profile_root_layout;
CoordinatorLayout layot_to_hide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profile_root_layout = (FrameLayout) findViewById(R.id.profile_activity);
layot_to_hide = (CoordinatorLayout) findViewById(R.id.layout_to_hide);
new userProfileTask().execute();
}
public class userProfileTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
new ProgressBarHandler(getBaseContext(),profile_root_layout,layot_to_hide).show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
new ProgressBarHandler(getBaseContext(),profile_root_layout,layot_to_hide).hide();
}
}
}
The progress bar never gets hides.Where I am doing mistake.
Make a separate class then make a static method with the parameter on it the parameter contain Activity ... call this method on ur activity and pass the Activity name in it
Its very simple, you can do in multiple ways.
1) You can define base activity and write your code for progress dialog and extends all activity from BaseActivity used Progressdialog.
2) You can have custom separate class and used in all activities.
etc
Here is good example you can modify your code like this example.
ProgressHud
Or use this too.
I would suggest create a dialog and call in your activity class like this
dialog = new Dialog(getActivity(), android.R.style.Theme_Black);
View views = LayoutInflater.from(getActivity()).inflate(R.layout.activity_dialog, null);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawableResource(R.color.feed_item_bg);
dialog.setContentView(views);
dialog.show();
and in your async task onPostExecute dismiss dialog
dialog.dismiss();
public static void getProgress(Activity activity,FrameLayout relativeLayout){
final ProgressBar pb;
int progressStatus = 0;
final Handler handler = new Handler();
pb = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
LayoutParams lp = new LayoutParams(550,LayoutParams.WRAP_CONTENT);
pb.setLayoutParams(lp);
LayoutParams params = (LayoutParams) pb.getLayoutParams();
pb.setLayoutParams(params);
pb.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
relativeLayout.addView(pb);
new Thread(new Runnable() {
#Override
public void run() {
int progressStatus = 0;
while(progressStatus < 100){
progressStatus +=1;
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
final int finalProgressStatus = progressStatus;
handler.post(new Runnable() {
#Override
public void run() {
pb.setProgress(finalProgressStatus);
}
});
}
}
}).start(); // Start the operation
}
You could use a parent Activity. This activity class extends AppCompatActivity . Other Activities will extend this Activity. For example the name of this activity is AbstractActivty.
public class AbstractActivty extends AppCompatActivity{
AlertDialog alertDialogProgressBar;
public void showLoadingProgressBar(String message, boolean cancalable) {
if (isActivityPaused)
return;
AlertDialog.Builder adb = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.alert_dialog_progressbar_layout,null);
TextView tv = (TextView) view.findViewById(R.id.idTextViewMessage);
tv.setText(message);
adb.setView(view);
alertDialogProgressBar = adb.create();
alertDialogProgressBar.setCancelable(cancalable);
alertDialogProgressBar.show();
}
public void closeProgressBar() {
if (alertDialogProgressBar == null) {
return;
}
alertDialogProgressBar.hide();
}
}
This class have a method which could be called by any other activity that extends
AbstractActivty
class MainActivty extends AbstractActivty{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// when require to show progressbar
showLoadingProgressBar("Loading....",true)
// when required to hide call
closeProgressBar();
}
}
Note in Alert Dialog we have used a custom layout
"alert_dialog_progressbar_layout.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/text_padding_l">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guidelineVertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent=".3"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guidelineVertical"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="#+id/idTextViewMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Loading...."
android:textColor="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/guidelineVertical"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Hope this will be of help . Thank you.

Overlay consumes all touch events

My app puts an invisible overlay on the left edge of the screen, and if the user swipes from the bottom half, I want to catch this event and do something with it. The problem is that instead of only the bottom half, all touch events on the upper half of the edge (which is 8dp wide) are also consumed and thus not passed to the app underneath it.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/llLauncher"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/transparentblack80"
android:visibility="gone">
<be.robinj.ubuntu.unity.launcher.AppLauncher
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:icon="#drawable/launcher_bfb"
custom:special="true"
android:onClick="lalBfb_clicked"
android:id="#+id/lalBfb"
android:layout_marginTop="2dp"
android:tag="partOfLauncher" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrLauncherAppsContainer"
android:scrollbars="none"
android:layout_weight="1"
android:fillViewport="false"
android:tag="partOfLauncher">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/llLauncherPinnedApps"
android:layout_gravity="top"
android:tag="partOfLauncher">
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/llListenerContainer"
android:orientation="vertical"
android:layout_width="8dp"
android:layout_height="match_parent"
android:weightSum="2"
android:gravity="bottom">
<LinearLayout
android:id="#+id/llListener"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#FF0000">
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/llShadow"
android:orientation="vertical"
android:layout_width="160dp"
android:layout_height="match_parent"
android:background="#drawable/launcherservice_shadow"
android:visibility="gone"
android:tag="shadow">
</LinearLayout>
</LinearLayout>
llListenerContainer and its child element llListener are what's of importance here. The other two elements are hidden by default and will be shown when a touch on the bottom half of the left edge of the screen is detected.
On the following screenshot I've made llListener visible by giving it a red background colour;
So touches inside the red area should be handled by my service, but touches on the upper half of the left edge should just be handled by the app underneath it.
Relevant Java code;
public class LauncherService extends Service
{
private WindowManager wm;
private TouchListener touchListener;
private LinearLayout layout;
private LinearLayout llListenerContainer;
private LinearLayout llListener;
private LinearLayout llLauncher;
private LinearLayout llShadow;
#Override
public IBinder onBind (Intent intent)
{ return null; }
#Override
public void onCreate ()
{
super.onCreate ();
this.wm = (WindowManager) this.getSystemService (WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) this.getSystemService (Service.LAYOUT_INFLATER_SERVICE);
this.layout = (LinearLayout) inflater.inflate (R.layout.service_launcher, null, false);
this.llLauncher = (LinearLayout) this.layout.findViewById (R.id.llLauncher);
this.llListenerContainer = (LinearLayout) this.layout.findViewById (R.id.llListenerContainer);
this.llListener = (LinearLayout) this.layout.findViewById (R.id.llListener);
this.llShadow = (LinearLayout) this.layout.findViewById (R.id.llShadow);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 0;
this.touchListener = new TouchListener (this);
lalBfb.setOnTouchListener (this.touchListener);
this.llListener.setOnTouchListener (this.touchListener);
this.llShadow.setOnTouchListener (this.touchListener);
this.wm.addView (this.layout, params);
}
#Override
public int onStartCommand (Intent intent, int flags, int id)
{
this.layout.setVisibility (intent.getBooleanExtra ("show", true) ? View.VISIBLE : View.GONE);
return super.onStartCommand (intent, flags, id);
}
#Override
public void onDestroy ()
{
super.onDestroy ();
this.wm.removeView (this.layout);
}
//# Event handlers #//
public void swipeRight ()
{
this.llLauncher.setVisibility (View.VISIBLE);
this.llShadow.setVisibility (View.VISIBLE);
this.llListenerContainer.setVisibility (View.GONE);
}
public void swipeLeft ()
{
this.llLauncher.setVisibility (View.GONE);
this.llShadow.setVisibility (View.GONE);
this.llListenerContainer.setVisibility (View.VISIBLE);
}
}
public class TouchListener implements View.OnTouchListener
{
private LauncherService parent;
public TouchListener (LauncherService parent)
{ this.parent = parent; }
#Override
public boolean onTouch (View view, MotionEvent event)
{
int id = view.getId ();
if (id == R.id.llListener)
{
this.parent.swipeRight ();
return true;
}
else if (id == R.id.llShadow)
{
this.parent.swipeLeft ();
return true;
}
return false;
}
}
I haven't had the opportunity to try this on a device yet, but it could be because you are defining the height of your parent layout to "match_parent".
Can you try changing that to "wrap_content" ?

UIL LinearBackground image not working

I've spent half day reading documentation and examples. I can't find a solution.
I've a ListView in an Activity, each item has LinearLayout with a background image loaded with Android-Universal-Image-Loader by nostr13.
I use this library to put a LinearBackground image as a background. In my Activity I download a JSON, parsing and creating a String array with the URIs.
The problem is the print done by the library is wrong! It works fine with ImageView but if I use LinearBackground with loadImage() intestead of displayImage() it doesn't put correctly the backgrounds. The procees seen at slow motion is like: create the right number of elements (4), place the first loaded image as background of one row, then once another image is loaded the library replaces the old background with this new image, different, then it places another image and stop. This is an example of the bug. It's always different!!! Some of them are empty but the onLoadingComplete event is called. I thought it was a problem of cache and I've played with the UIL's options without luck. Images are just 4 and very small (<10kb each).
I set the adapter in the onPostExecute event, is it ok?
What can be the problem?
Here the important code:
The Activity code (i've removed not relevant code to help to find the problem):
public class myActivity extends Activity {
Context context;
// Output Vars
String mStrings[];
ListView listView;
// UIL
DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_left);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_stagioni);
listView = (ListView) findViewById(R.id.listView);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.fail)
.showImageOnFail(R.drawable.fail)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.build();
startAsynkTask(context);
}
public void startAsynkTask(final Context context) {
AsyncTask<String, Void, Void> task = new AsyncTask<String, Void, Void>() {
private ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(ActivityStagioni.this);
pd.setTitle(getResources().getString(R.string.dialog_loading));
pd.setMessage(getResources().getString(R.string.dialog_loading_stagioni));
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(true);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(String... arg0) {
//... Not relevant code ...
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
((ListView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener()
{
//... Not relevant code ...
});
}
};
task.execute();
}
public class ImageAdapter extends BaseAdapter {
ImageLoader imageLoader;
public ImageAdapter() {
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.stagioni_item, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (LinearLayout) view.findViewById(R.id.linearLayoutLocandina);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
imageLoader.loadImage(mStrings[position], new SimpleImageLoadingListener() {
//final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
//if (loadedImage != null) {
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
BitmapDrawable background = new BitmapDrawable(loadedImage);
holder.imageView.setBackgroundDrawable(background);
//}
// }
}
});
return view;
}
The ListView item is:
<?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="match_parent"
android:background="#color/black"
android:orientation="horizontal"
android:weightSum="5"
android:baselineAligned="false">
<LinearLayout
android:id="#+id/linearLayoutLocandina"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_margin="0dp"
android:layout_weight="1"
android:background="#drawable/ic_launcher"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="25dp"
android:layout_weight="5" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="25dp"
android:layout_weight="5"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0"
android:alpha="1"
android:background="#80000000" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_NumeroStagione"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="bottom|center_horizontal"
android:text="30"
android:textColor="#color/white"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_NomeStagione"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_weight="0"
android:text="TextView"
android:textColor="#color/white" />
<TextView
android:id="#+id/textView_NumeroEpisodi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="TextView"
android:textColor="#color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_objectID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="100"
android:layout_gravity="bottom"
style="#style/ProgressBarStyle" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Application
public class MyAppName extends Application {
#Override
public void onCreate() {
super.onCreate();
initImageLoader(getApplicationContext());
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
}
Logcat
http://pastebin.com/JejB8miC
Thanks for support
Add this ImageAware into your project:
public class BgImageAware implements ImageAware {
public static final String WARN_CANT_SET_DRAWABLE = "Can't set a drawable into view. You should call ImageLoader on UI thread for it.";
public static final String WARN_CANT_SET_BITMAP = "Can't set a bitmap into view. You should call ImageLoader on UI thread for it.";
protected Reference<View> viewRef;
protected boolean checkActualViewSize;
public BgImageAware(View view) {
this(view, true);
}
public BgImageAware(View view, boolean checkActualViewSize) {
this.viewRef = new WeakReference<View>(view);
this.checkActualViewSize = checkActualViewSize;
}
#Override
public int getWidth() {
View view = viewRef.get();
if (view != null) {
final ViewGroup.LayoutParams params = view.getLayoutParams();
int width = 0;
if (checkActualViewSize && params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT) {
width = view.getWidth(); // Get actual image width
}
if (width <= 0 && params != null) width = params.width; // Get layout width parameter
return width;
}
return 0;
}
#Override
public int getHeight() {
View view = viewRef.get();
if (view != null) {
final ViewGroup.LayoutParams params = view.getLayoutParams();
int height = 0;
if (checkActualViewSize && params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
height = view.getHeight(); // Get actual image height
}
if (height <= 0 && params != null) height = params.height; // Get layout height parameter
return height;
}
return 0;
}
#Override
public ViewScaleType getScaleType() {
return ViewScaleType.CROP;
}
#Override
public View getWrappedView() {
return viewRef.get();
}
#Override
public boolean isCollected() {
return viewRef.get() == null;
}
#Override
public int getId() {
View view = viewRef.get();
return view == null ? super.hashCode() : view.hashCode();
}
#Override
public boolean setImageDrawable(Drawable drawable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
View view = viewRef.get();
if (view != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
return true;
}
} else {
L.w(WARN_CANT_SET_DRAWABLE);
}
return false;
}
#Override
public boolean setImageBitmap(Bitmap bitmap) {
if (Looper.myLooper() == Looper.getMainLooper()) {
View view = viewRef.get();
if (view != null) {
Drawable drawable = bitmap == null ? null : new BitmapDrawable(view.getResources(), bitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
return true;
}
} else {
L.w(WARN_CANT_SET_BITMAP);
}
return false;
}
}
And then wrap your LinearLayout into it and pass to displayImage(...) method:
ImageAware imageAware = new BgImageAware(holder.imageView);
imageLoader.displayImage(mStrings[position], imageAware);

Phone won't play the on-click sound

I am currently developing an android application in which purpose is to play a large variety of every-day sounds on click.
I have 3 activities : home, animaux and transports.
Home is fine, animaux is fine (it plays all the sounds without any problems).
But I want to integrate admob on Transports acivity. Ads display well, but when I cluck on the sounds buttons, nothing happens. If you could help me understand my mistake and how to fix it, it would be very nice !
Here is transports.java
public class Transports extends Activity {
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxx"
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private MediaPlayer mPlayer = null;
/** Called when the activity is first created. */
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
Button btn_sound_sncf2 = (Button) findViewById(R.id.sncfnew);
btn_sound_sncf2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.sncf2);
}
});
Button btn_sound_sncf1 = (Button) findViewById(R.id.sncf1);
btn_sound_sncf1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.sncf1);
}
});
}
#Override
public void onPause() {
super.onPause();
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
}
private void playSound(int resId) {
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
And here is the transports.xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_vertical"
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=".Transports" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="left"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxx"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
android:gravity="top" >
</com.google.ads.AdView>
<Button android:id="#+id/sncfnew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/sncf1"
android:layout_below="#+id/sncf1"
android:layout_marginTop="38dp"
android:text="#string/sncfnew" />
<Button android:id="#+id/sncf1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/linearLayout1"
android:text="#string/sncf1" />
</LinearLayout>
</RelativeLayout>
I wonder if the problem isn't in my xml file : I have a lot of difficulties to maker a clear interface with the linearlayout required by admob.
You aren't actually setting the listeners. You have that code in a method:
public void onCreate1(Bundle savedInstanceState) {
that is never called. Move that code to the actual onCreate() method and it should work fine.

Categories