communication between two device using sms - javascript

I want my program to be able to receive sms from a special number("+9856874236").
I want application to be recive SMS ,if the SMS is contain "enable wifi" ,then change wifi to enable
i 'm using this code but it working crash??
MainActivity
package com.example.sms;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
static TextView messageBox;
static String x="";
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox=(TextView)findViewById(R.id.messageBox);
check();
}
//How to used other or many activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static void updateMessageBox(String msg,String from)
{
messageBox.append(msg);
//Get parent phone number from database
//check parent number with ...
if(msg.equals("enable wifi"))
{
x="yes";
MainActivity objSampleClass = new MainActivity();
objSampleClass.check();
}
//context.startActivity(new Intent(context, MainActivity.class));
//Intent i=new Intent(context, p1.class);
//context.startActivity(i);
}
public void check()
{
if(x.equals("yes"))
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
else
{
}
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.sms.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.sms.TextMessageReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name="com.example.sms.Test"
android:label="#string/title_activity_test" >
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
</manifest>

To intercept the SMS as early as possible I use the following code:
public class Communicator extends Service {
private final String TAG = this.getClass().getSimpleName();
private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;
#Override
public void onCreate()
{
super.onCreate();
Log.i(TAG, "Communicator started");
//SMS event receiver
mSMSreceiver = new SMSReceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
mIntentFilter.setPriority(2147483647);
registerReceiver(mSMSreceiver, mIntentFilter);
Intent intent = new Intent("android.provider.Telephony.SMS_RECEIVED");
List<ResolveInfo> infos = getPackageManager().queryBroadcastReceivers(intent, 0);
for (ResolveInfo info : infos) {
Log.i(TAG, "Receiver name:" + info.activityInfo.name + "; priority=" + info.priority);
}
}
#Override
public void onDestroy()
{
super.onDestroy();
// Unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
private class SMSReceiver extends BroadcastReceiver
{
private final String TAG = this.getClass().getSimpleName();
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extras = intent.getExtras();
String strMessage = "";
if ( extras != null )
{
Object[] smsextras = (Object[]) extras.get( "pdus" );
for ( int i = 0; i < smsextras.length; i++ )
{
SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);
String strMsgBody = smsmsg.getMessageBody().toString();
String strMsgSrc = smsmsg.getOriginatingAddress();
strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody;
Log.i(TAG, strMessage);
if (strMsgBody.contains("SomeText")) {
// perform code
this.abortBroadcast();
}
}
}
}
}
}
Remember to register the service in manifest:
<service android:name="yourpackage.Communicator" />
Now in onCreate and onDestroy start and stop the service:
startService(new Intent(this, Communicator.class));
stopService(new Intent(this, Communicator.class));

In your BroadcastReceiver use following code,
Uri uri = Uri.parse("content://sms/");
ContentResolver contentResolver = getContentResolver();
String phoneNumber = "+9856874236";
String sms = "address='"+ phoneNumber + "'";
Cursor cursor = contentResolver.query(uri, new String[] { "_id", "body" }, "read = 0 and address='" + sms, null, null);
if ( cursor.getCount() > 0 )
{
// perform action to start Wifi Connection
}
Also in AndroidManifest.xml file you need to set Priority for reading SMS by your application as follows,
<receiver android:name="com.example.sms.TextMessageReceiver" >
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

Related

androidx.appcompat.widget.LinearLayoutCompat cannot be cast to android.widget.LinearLayout

I have an Android app. This app has ten activities, the first activity of which is the Splash Screen that is run thats After one or two seconds, the app closes and does not enter the second activity The error I get is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 4538
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.IntroPage}: java.lang.ClassCastException: androidx.appcompat.widget.LinearLayoutCompat cannot be cast to android.widget.LinearLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.LinearLayoutCompat cannot be cast to android.widget.LinearLayout
at com.example.myapplication.IntroPage.onCreate(IntroPage.java:45)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
thats my xml splash screen code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".SplashScreen"
android:background="#color/White">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/img_gif"
android:layout_width="match_parent"
android:layout_height="289dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="38dp"
android:src="#drawable/ic_profile"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.296" />
<androidx.core.widget.ContentLoadingProgressBar
android:id="#+id/progress"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.005"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.github.ybq.android.spinkit.SpinKitView
android:id="#+id/spin_kit"
style="#style/SpinKitView.WanderingCubes"
android:layout_width="60dp"
android:layout_height="49dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="36dp"
android:layout_marginRight="8dp"
app:SpinKit_Color="#color/orange"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/img_gif"
app:layout_constraintVertical_bias="0.254" />
<TextView
android:id="#+id/textView2"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="8dp"
android:layout_marginBottom="2dp"
android:gravity="center"
android:text="#string/powerd_by_maede"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/spin_kit"
app:layout_constraintVertical_bias="0.48"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
thats my xml for sec activity:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9bfa5e">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="0dp"
android:layout_height="435dp"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/layoutDots"
app:layout_constraintRight_toRightOf="#+id/layoutDots"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="8dp"
app:layout_constraintLeft_toRightOf="#+id/layoutDots" />
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/layoutDots"
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:orientation="horizontal"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent" />
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:alpha=".5"
android:background="#222"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/btn_next"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="#+id/btn_next" />
<Button
android:id="#+id/btn_next"
android:layout_width="88dp"
android:layout_height="50dp"
android:background="#drawable/chevron_right"
android:textColor="#222"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintLeft_toRightOf="#+id/btn_skip"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1" />
<Button
android:id="#+id/btn_skip"
android:layout_width="88dp"
android:layout_height="48dp"
android:layout_marginBottom="1dp"
android:background="#null"
android:text="رد کردن"
android:textColor="#ffffff"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/layoutDots"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1" />
</androidx.constraintlayout.widget.ConstraintLayout>
thats my splash screen activity:
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.ProgressBar;
import com.github.ybq.android.spinkit.sprite.Sprite;
import com.github.ybq.android.spinkit.style.DoubleBounce;
import java.util.Calendar;
public class SplashScreen extends AppCompatActivity {
SharedPreferences sharedP;
boolean show_intropage=true;
Calendar taqwim = Calendar.getInstance();
int today,date_mod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//----progress---------------
ProgressBar progressBar = findViewById(R.id.progress);
Sprite doubleBounce = new DoubleBounce();
progressBar.setIndeterminateDrawable(doubleBounce);
today = taqwim.get(Calendar.DAY_OF_YEAR);
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);
sharedP.edit().putInt(Items.TODAY, today).apply();
if (show_intropage){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent Myintent = new Intent(SplashScreen.this,IntroPage.class);
startActivity(Myintent);
finish();
}
},4000);
date_mod = taqwim.get(Calendar.DAY_OF_YEAR);
// Toast.makeText(this, day+"", Toast.LENGTH_SHORT).show();
sharedP.edit().putInt(Items.DATE_MODIFIED, date_mod).apply();
}else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent Myintent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(Myintent);
finish();
}
},4000);
}
}
}
thats my sec activity:
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ToxicBakery.viewpager.transforms.RotateUpTransformer;
public class IntroPage extends AppCompatActivity {
ViewPager MyviewPager;
Button btnSkip, btnNext;
private LinearLayout dotsLayout;
private TextView[] dots;
SharedPreferences sharedP;
int [] layout = {R.layout.slide_01,R.layout.slide_02,R.layout.slide_04};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro_page);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
MyviewPager = (ViewPager) findViewById(R.id.viewpager);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
MyviewPager.setAdapter(new ViewP());
MyviewPager.setPageTransformer(true, new RotateUpTransformer());
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
addBottomDots(0);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int Tedad_items = MyviewPager.getCurrentItem()+1;
if (Tedad_items < layout.length) {
MyviewPager.setCurrentItem(MyviewPager.getCurrentItem()+1);
} else {
startActivity(new Intent(IntroPage.this,MainActivity.class));
finish();
}
}
});
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(IntroPage.this,MainActivity.class));
finish();
}
});
MyviewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
if (position == layout.length - 1) {
// btnNext.setText("Start");
btnNext.setBackgroundResource(R.drawable.check);
btnSkip.setVisibility(View.GONE);
} else {
// btnNext.setText("Next");
btnNext.setBackgroundResource(R.drawable.chevron_right);
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public class ViewP extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view= LayoutInflater.from(IntroPage.this).inflate(layout[position],container,false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layout.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// View view = (View)object;
container.removeView((View) object);
}
}
private void addBottomDots(int currentPage) {
dots = new TextView[layout.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[0]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[0]);
}
}
The issue is here:
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
In your layout you are using a LinearLayoutCompat.
Use:
LinearLayoutCompat dotsLayout;
dotsLayout = findViewById(R.id.layoutDots);

Only image text is showing from firebase in recyclerview fragment Image is not loading [duplicate]

This question already has an answer here:
My recycler view is not showing any firebase images
(1 answer)
Closed 2 years ago.
My images from firebase are not showing in image view but the name of an image is showing in the above text view of the recycler view. Here is my code please help.
FragmentActivity
package com.example.bbeast.HomeActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.bbeast.R;
import com.example.bbeast.Upload;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class fragmentHealthTips extends Fragment {
private RecyclerView mRecyclerView;
private DatabaseReference mDataRef;
private Uri mImageuri;
View view;
public void fragmentHealthTips() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.healthtips_fragment, container, false);
mRecyclerView =(RecyclerView)view.findViewById(R.id.healthtips_recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mDataRef = FirebaseDatabase.getInstance().getReference().child("Uploads");
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<HealthTips>()
.setQuery(mDataRef, HealthTips.class)
.build();
FirebaseRecyclerAdapter<HealthTips, hViewHolder> adapter= new FirebaseRecyclerAdapter<HealthTips, hViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final hViewHolder holder, int i, #NonNull final HealthTips healthTips) {
//directly get the values like this
String Iname = healthTips.getName();
String Uimage = healthTips.getImage();
holder.hName.setText(Iname);
Picasso.get()
.load(Uimage)
.into(holder.hImageview);
}
#NonNull
#Override
public hViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_healthtips, parent, false);
hViewHolder viewHolder = new hViewHolder(view);
return viewHolder;
}
};
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class hViewHolder extends RecyclerView.ViewHolder{
TextView hName;
ImageView hImageview;
public hViewHolder(#NonNull View itemView) {
super(itemView);
hName = itemView.findViewById(R.id.healthtips_name);
hImageview = itemView.findViewById(R.id.healthtips_imageView);
}
}
}
Xml file of items.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/healthtips_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"/>
<ImageView
android:id="#+id/healthtips_imageView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="20dp"
android:background="#drawable/imageview_bg"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Model class, Healthtips activity.
package com.example.bbeast.HomeActivity;
import java.util.jar.Attributes;
public class HealthTips {
public String name, image;
public HealthTips(){
}
public HealthTips(String name, String image){
this.name = name;
this.image = image;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getImage(){
return image;
}
public void setImage(String image){
this.image= image;
}
}
Gradle dependencies.
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.bbeast"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
dataBinding {
enabled = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java/Admin Activity', 'src/main/java/com.example.bbeast/ui.main/Admin Activity']
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-storage:16.0.4'
implementation 'com.firebaseui:firebase-ui-database:3.2.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.firebase:firebase-analytics:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.squareup.picasso:picasso:2.6.0-SNAPSHOT'
}
Please help me in getting an image in the image view. Thank you in advance.
Check
of the UImage is a valid path, normally I would do something like this..
P.S Not a RecyclerView but you get the idea
imageview1 = (ImageView) findViewById(R.id.imageview1);
_path_child_listener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot _param1, String _param2) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
Glide.with(getApplicationContext()).load(Uri.parse(_childValue.get("imageUrl").toString())).into(imageview1);
//imageUrl is pushed to Firebase Storage onUploadCompleted
}
#Override
public void onChildChanged(DataSnapshot _param1, String _param2) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
}
#Override
public void onChildMoved(DataSnapshot _param1, String _param2) {
}
#Override
public void onChildRemoved(DataSnapshot _param1) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
}
#Override
public void onCancelled(DatabaseError _param1) {
final int _errorCode = _param1.getCode();
final String _errorMessage = _param1.getMessage();
}
};
path.addChildEventListener(_path_child_listener);
}
private void initializeLogic() {
}

Alarm playing with audio in the background Irregular?

I've used AlarmManager ,so it works every minute
every minute, service class is called
and it keeps working even after it's turned off
it's got a sound in the back of the device
the idea works when i run the app inside Android Studio on device 5.1.1
but i noticed when i disconnected the device from the cable.
alerts are irregular and audio works
other times.
//
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(getApplicationContext(), RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
1 * 60 * 100 , pendingIntent);
}
}
// ---
public class RingAlarm extends Service {
MediaPlayer sound2;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "الحمد لله", Toast.LENGTH_LONG).show();
sound2 = (MediaPlayer) MediaPlayer.create(RingAlarm.this,R.raw.a2);
sound2.start();
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0){
// TODO Auto-generated method stub
return null;
}
}
//
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ahmedco.testcode">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".RingAlarm" />
</application>
</manifest>

Newbie project - start an activity from BroadcastReceive

I'm trying to build a simple daily reminder app as my first Android
project and I'm just stucked now. Too much information from hours
watching tutorials. :)
So I would like some help to understand the code behind
my idea so hopefully someone explains this with ease :)
Three times a day I want an alarm/reminder/splash to set off for ten seconds
with different pictures and sounds depending on the alarmtime.
An ability to tap/swipe to stop it before 10 seconds.
alarm1
---alarm1time08:10
---alarm1pic1.jpg
---alarm1Sound1.mp3
alarm2
---alarm2time12:30
---alarm2pic1.jpg
---alarm2Sound1.mp3
alarm3
---alarm3time18:45
---alarm3pic1.jpg
---alarm3Sound1.mp3
So how do I do this?
I'm using Android Studio 2.3 (to slow computer for 3.x...),
Java and my phones are Lollipop 5.1 API level 22 and
Marshmallow 6.0 API level 23
This is my code that actually works without error..
But now i don't know how open an activity with my image and sounds.
I got a RED startActivity when I tried it in hRec.
MainActivity.java
package com.hlm.myreminder;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hHour1 = 08;
int hMin1 = 10;
Calendar hCal1 = Calendar.getInstance();
hCal1.set(Calendar.HOUR_OF_DAY, hHour1);
hCal1.set(Calendar.MINUTE, hMin1);
hCal1.set(Calendar.SECOND, 0);
Log.v("hLogging","cal set");
Intent hIntent = new Intent(getApplication(),hRec.class);
PendingIntent hPi = PendingIntent.getBroadcast(getApplicationContext(),0,hIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Log.v("hLogging","intent set");
AlarmManager hAlMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
hAlMgr.setRepeating(AlarmManager.RTC_WAKEUP,hCal1.getTimeInMillis(),hAlMgr.INTERVAL_DAY,hPi);
Log.v("hLogging","am set");
// startActivity(new Intent(this, hshowreminderpic1.class)); //works
// Log.v("hLogging","goto hshowreminderpic1 done"); //works
}
}
hRec.java
package com.hlm.myreminder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class hRec extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent hIntent) {
Log.d("hLogging", "hRec:BroadcastReceiverAlarm");
// show hshowreminderpic1
/* startActivity gets RED */
// startActivity(new Intent(this, hshowreminderpic1.class));
// Log.v("hLogging","goto hshowreminderpic1 request");
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hlm.myreminder">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#drawable/h_icon72"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".hshowreminderpic1"/>
<receiver android:name=".hRec"></receiver>
</application>
</manifest>
You need to pass context to start your activity from hRec.java as hRec is not an activity.
So simply write
Intent i = new Intent(context, hshowreminderpic1.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Try using this:
context.startActivity(new Intent(this, hshowreminderpic1.class));

In wallpaper app i am getting Gap beside the image in fullScreenView

Plz Look at the below image i am getting Gap beside the image in full screen view anyone plz help
Please have a look on my code and tell me what's wrong with it.
If there is any solution plz explain me clearly step-by-step (I am New to android)
Gap Beside Image
package com.saveitornot.wallit;
FullscreenViewActivity.java
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.saveitornot.wallit.app.AppController;
import com.saveitornot.wallit.picasa.model.Wallpaper;
import com.saveitornot.wallit.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FullScreenViewActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = FullScreenViewActivity.class
.getSimpleName();
public static final String TAG_SEL_IMAGE = "selectedImage";
private Wallpaper selectedPhoto;
private ImageView fullImageView;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
private CoordinatorLayout coordinatorLayout;
private int progressStatus = 0;
private Handler handler = new Handler();
private String licencseURL,licenseeURL = null;
// Picasa JSON response node keys
private static final String TAG_ENTRY = "entry",
TAG_MEDIA_GROUP = "media$group",
TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url",
TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height";
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
pbLoader.setIndeterminate(true);
pbLoader.setMax(100);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
Intent i = getIntent();
selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE);
// check for selected photo null
if (selectedPhoto != null) {
// fetch photo full resolution image by making another json request
fetchFullResolutionImage();
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT)
.show();
}
}
/**
* Fetching image fullresolution json
* */
private void fetchFullResolutionImage() {
String url = selectedPhoto.getPhotoJson();
// show loader before making request
pbLoader.setVisibility(View.VISIBLE);
llSetWallpaper.setVisibility(View.GONE);
llDownloadWallpaper.setVisibility(View.GONE);
getSupportActionBar().hide();
// volley's json obj request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,
"Image full resolution json: "
+ response.toString());
try {
// Parsing the json response
JSONObject entry = response
.getJSONObject(TAG_ENTRY);
JSONArray mediacontentArry = entry.getJSONObject(
TAG_MEDIA_GROUP).getJSONArray(
TAG_MEDIA_CONTENT);
JSONObject mediaObj = (JSONObject) mediacontentArry
.get(0);
String fullResolutionUrl = mediaObj
.getString(TAG_IMG_URL);
// image full resolution widht and height
final int width = mediaObj.getInt(TAG_IMG_WIDTH);
final int height = mediaObj.getInt(TAG_IMG_HEIGHT);
Log.d(TAG, "Full resolution image. url: "
+ fullResolutionUrl + ", w: " + width
+ ", h: " + height);
ImageLoader imageLoader = AppController
.getInstance().getImageLoader();
// We download image into ImageView instead of
// NetworkImageView to have callback methods
// Currently NetworkImageView doesn't have callback
// methods
///
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus<100){
progressStatus += 1;
handler.post(new Runnable() {
#Override
public void run() {
pbLoader.setProgress(progressStatus);
}
});
try {
Thread.sleep(100);
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}).start();
///
imageLoader.get(fullResolutionUrl,
new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(
VolleyError arg0) {
Toast.makeText(
getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(
ImageLoader.ImageContainer response,
boolean arg1) {
if (response.getBitmap() != null) {
// load bitmap into imageview
fullImageView
.setImageBitmap(response
.getBitmap());
adjustImageAspect(width, height);
// hide loader and show set &
// download buttons
pbLoader.setVisibility(View.GONE);
llSetWallpaper
.setVisibility(View.VISIBLE);
llDownloadWallpaper
.setVisibility(View.VISIBLE);
getSupportActionBar().show();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
// unable to fetch wallpapers
// either google username is wrong or
// devices doesn't have internet connection
Toast.makeText(getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
});
// Remove the url from cache
AppController.getInstance().getRequestQueue().getCache().remove(url);
// Disable the cache for this url, so that it always fetches updated
// json
jsonObjReq.setShouldCache(false);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Adjusting the image aspect ration to scroll horizontally, Image height
* will be screen height, width will be calculated respected to height
* */
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
if (bWidth == 0 || bHeight == 0)
return;
int sHeight = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
sHeight = size.y;
} else {
Display display = getWindowManager().getDefaultDisplay();
sHeight = display.getHeight();
}
int new_width = (int) Math.floor((double) bWidth * (double) sHeight
/ (double) bHeight);
params.width = new_width;
params.height = sHeight;
Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width
+ ", h = " + sHeight);
fullImageView.setLayoutParams(params);
}
/**
* View click listener
* */
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (v.getId()) {
// button Download Wallpaper tapped
case R.id.llDownloadWallpaper:
utils.saveImageToSDCard(bitmap, coordinatorLayout);
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
utils.setAsWallpaper(bitmap, coordinatorLayout);
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_fullscreen, menu);
return true;
}
private void gotoURL(String url)
{
Uri uri = Uri.parse(url);
Intent goToWebsite = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
if (Build.VERSION.SDK_INT >= 21)
{
flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
}
else
{
//noinspection deprecation
flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
}
goToWebsite.addFlags(flags);
try {
startActivity(goToWebsite);
} catch (ActivityNotFoundException e) {
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (id) {
case android.R.id.home:
finish();
return true;
case R.id.action_set_as_wallpaper:
utils.setAsWallpaper(bitmap, coordinatorLayout);
return true;
case R.id.action_download:
utils.saveImageToSDCard(bitmap, coordinatorLayout);
return true;
case R.id.action_share:
utils.shareImage(bitmap, coordinatorLayout);
return true;
case R.id.action_report:
utils.reportImage(bitmap);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ManiActivity.java
package com.saveitornot.wallit;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.saveitornot.wallit.app.AppController;
import com.saveitornot.wallit.picasa.model.Category;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private List<Category> albumsList;
private ArrayList<NavDrawerItem> navDrawerItems;
String name = new String("Main Grid Screen");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Getting the albums from shared preferences
albumsList = AppController.getInstance().getPrefManger().getCategories();
// Insert "Recently Added" in navigation drawer first position
/* Category recentAlbum = new Category(null, getString(R.string.nav_drawer_recently_added), "(100)");
albumsList.add(0, recentAlbum);*/
// Loop through albums in add them to navigation drawer adapter
for (Category a : albumsList) {
navDrawerItems.add(new NavDrawerItem(true, a.getId(), a.getTitle(), a.getPhotoNo()));
// titles a.getTitle()
}
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
displayView(0);
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String albumId = "";
switch (position) {
case 0:
// Recently added item selected
// don't pass album id to grid fragment
/*Log.e(TAG, "GridFragment is creating");
fragment = GridFragment.newInstance(null);*/
albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
break;
default:
// selected wallpaper category
// send album id to grid fragment to list all the wallpapers
albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(albumsList.get(position).getTitle());
} else {
// error in creating fragment
Log.e(TAG, "Error in creating fragment");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
}
Here is an XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FullScreenViewActivity">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black" >
<ProgressBar
android:id="#+id/pbLoader"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:progressTint="#color/colorPrimary"
android:progressBackgroundTint="#color/white"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1">
</ProgressBar>
<!-- Scroll view for fullscreen preview -->
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/imgFullscreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
</LinearLayout>
</HorizontalScrollView>
<!-- Set as wallpaper button -->
<LinearLayout
android:id="#+id/llSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ico_apply" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="#string/set_wallpaper"
android:textColor="#color/white"
android:textSize="18dp" />
</LinearLayout>
<!-- Download wallpaper button -->
<LinearLayout
android:id="#+id/llDownloadWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ico_download" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="#string/download_wallpaper"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/fragmentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
try change the android:layout_width="wrap_content" to android:layout_width="match_parent". Does it help?
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black" >
<ProgressBar
android:id="#+id/pbLoader"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:progressTint="#color/colorPrimary"
android:progressBackgroundTint="#color/white"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1">
</ProgressBar>
<!-- Scroll view for fullscreen preview -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgFullscreen"
android:src="#drawable/img_onboarding_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</LinearLayout>
</ScrollView>
<!-- Set as wallpaper button -->
<LinearLayout
android:id="#+id/llSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#drawable/icon_cashback"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/fas_void" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="wallpaper"
android:textColor="#color/white"
android:textSize="18dp" />
</LinearLayout>
<!-- Download wallpaper button -->
<LinearLayout
android:id="#+id/llDownloadWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/icon_cashback_ds"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/icon_flag_default" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="1234"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/fragmentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
That is how i modify your layout. I can see the image fill up the screen.

Categories