Facing problem while viewing and downloading wallpapers in new activity - java

I'm creating a Wallpaper application. I'm done with the categories and wallpapers inside each category using Picasso. And now I tried to make a new activity to view and download any wallpaper using Picasso. But after coding, when I click on the wallpaper the new activity never opens. Also there is no relevant error showing on the LogCat. Please help!
Here is the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.umarkhan.walldeck">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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/FullScreenTheme">
<activity android:name=".ViewWallpaper"></activity>
<activity android:name=".ListWallpaper" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/FullScreenTheme" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context="me.umarkhan.walldeck.ViewWallpaper">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="350dp">
<ImageView
android:id="#+id/imageThumb"
android:contentDescription="WallDeck Wallpaper"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="590dp"
android:clipToPadding="false"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
tools:layout_editor_absoluteY="352dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
app:cardElevation="10dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:padding="12dp"
android:text="Wallpaper description"
android:textSize="20sp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabWallpaper"
android:layout_marginRight="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_terrain_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end"
android:backgroundTint="#android:color/white"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabDownload"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_file_download_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|left|start"
android:backgroundTint="#android:color/white"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
SaveImageHelper Class
package me.umarkhan.walldeck.Helper;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.lang.ref.WeakReference;
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> alertDialogWeakReference;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context, AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.alertDialogWeakReference =new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference =new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
alertDialog.dismiss();
Toast.makeText(context,"Download Successful", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
context.startActivity(Intent.createChooser(intent,"View Picture"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
ViewWallpaper Class
package me.umarkhan.walldeck;
import android.Manifest;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import com.squareup.picasso.Target;
import java.util.UUID;
import dmax.dialog.SpotsDialog;
import me.umarkhan.walldeck.Common.Common;
import me.umarkhan.walldeck.Helper.SaveImageHelper;
public class ViewWallpaper extends AppCompatActivity {
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton floatingActionButton,fabDownload;
ImageView imageView;
CoordinatorLayout rootLayout;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
}
}
private Target target = new Target(){
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_wallpaper);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Init
rootLayout = (CoordinatorLayout)findViewById(R.id.rootLayout);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setTitle(Common.CATEGORY_SELECTED);
imageView = (ImageView)findViewById(R.id.imageThumb);
Picasso.with(this)
.load(Common.select_background.getimageLink())
.into(imageView);
floatingActionButton = (FloatingActionButton)findViewById(R.id.fabWallpaper);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(target);
}
});
fabDownload = (FloatingActionButton)findViewById(R.id.fabDownload);
fabDownload.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
//Check Permission
if (ActivityCompat.checkSelfPermission(ViewWallpaper.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, Common.PERMISSION_REQUEST_CODE);
return;
}
else
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
}
});
}
#Override
protected void onDestroy() {
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
I have already requested External Write Permission in HomeActivity:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
break;
}
}
private AppBarConfiguration mAppBarConfiguration;
private Object Context;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("WallZone Pro");
setSupportActionBar(toolbar);
// Request Runtime Permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},Common.PERMISSION_REQUEST_CODE);
}
Please help!

Please add the class from which to go to ViewWallpaper.class

Related

Problem in translation display in translation app on android studio

Hello eveyone i hope you are all doing good. I have a little problem and I couldn't find the solution. I have a translation app and after the user input his phrase by a record, the translation message doesn't appear. So I hope that someone could help me.
Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="#+id/idBtnTranslateLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TransledText"
android:layout_centerInParent="true"
android:text="Translate language" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:layout_marginTop="128dp"
android:background="#color/white"
android:padding="40dp"
android:src="#drawable/ic_baseline_mic_24" />
<TextView
android:id="#+id/TransledText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edittext"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:gravity="center_horizontal"
android:text="Translated language"
android:textAlignment="center"
android:textSize="20sp"
tools:ignore="UnknownId" />
</RelativeLayout>
And my main code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
public class MainActivity extends AppCompatActivity {
private static final int CodeSpeechInput =100;
private TextView EditText;
private ImageButton SpeakButton;
private TextView TransledText;
FirebaseTranslator englishFrenshTranslator;
private Button translateLanguageBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(FirebaseTranslateLanguage.EN)
.setTargetLanguage(FirebaseTranslateLanguage.FR)
.build();
englishFrenshTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
EditText = (TextView) findViewById(R.id.edittext);
SpeakButton = (ImageButton) findViewById(R.id.button);
TransledText = (TextView) findViewById(R.id.TransledText);
translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = EditText.getText().toString();
downloadModal(string);
}
private void downloadModal(String input) {
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
englishFrenshTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// this method is called when modal is downloaded successfully.
Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
// calling method to translate our entered text.
translateLanguage(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
}
});
}
private void translateLanguage(String input) {
englishFrenshTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String result) {
TransledText.setText(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
}
});
}
});
SpeakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
try {
startActivityForResult(intent, CodeSpeechInput);
} catch (ActivityNotFoundException a) {
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CodeSpeechInput : {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
EditText.setText(result.get(0));
}
break;
}
}
}
}
I also use firebase if that could help you.

Can't find nearby WiFi- Direct devices showing "No Device Found!"

I am trying to Discover two devices each other using WifiDirect. Devices are running Android version 8.0 and 9.0 respectively. But not able to succeed.
First time I click on Discover button on both devices both waits for 2-3 seconds and shows No device found Toast.
Second time I try to discover on both within a second both show up the No device found Toast.
MainActivity.java
package com.example.prototypewfp2p;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, ConnectoinStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mMangaer;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
// Permissions Related
public String[] PermissionsList = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE
, Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION};
public int permsRequestCode = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permissions
for (int i = 0; i < PermissionsList.length; i++) {
if (ContextCompat.checkSelfPermission(MainActivity.this, PermissionsList[i]) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PermissionsList, permsRequestCode);
}
} else {
Toast.makeText(MainActivity.this, "Permissions Granted Already!", Toast.LENGTH_SHORT).show();
}
}
//Calling Functions Declared below
initialWork();
exqListener();
}
//Permission (Override stuff)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (permsRequestCode) {
case 200:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission[1] granted!",Toast.LENGTH_LONG);
}
else{Toast.makeText(this,"Permission[1] Denied!",Toast.LENGTH_LONG);}
if(grantResults.length > 0 && grantResults[2] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 3 granted");}
if(grantResults.length > 0 && grantResults[3] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 4 granted");}
if(grantResults.length > 0 && grantResults[4] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 5 granted");}
if(grantResults.length > 0 && grantResults[5] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 6 granted");}
if(grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 2 granted");}
// boolean first = grantResults[0] == PackageManager.PERMISSION_GRANTED;
// boolean second = grantResults[1] == PackageManager.PERMISSION_GRANTED;
// boolean third = grantResults[2] == PackageManager.PERMISSION_GRANTED;
// boolean fourth = grantResults[3] == PackageManager.PERMISSION_GRANTED;
// boolean fifth = grantResults[4] == PackageManager.PERMISSION_GRANTED;
// boolean sixth = grantResults[5] == PackageManager.PERMISSION_GRANTED;
break;
}
}
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
// Toast.makeText(MainActivity.this,"Wifi is turned OFF",Toast.LENGTH_LONG).show();
} else {
wifiManager.setWifiEnabled(true);
// Toast.makeText(MainActivity.this,"Wifi is turned ON",Toast.LENGTH_LONG).show();
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
return;
}
mMangaer.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
ConnectoinStatus.setText("Discovery Started!");
}
#Override
public void onFailure(int reason) {
ConnectoinStatus.setText("Could not start Discovery");
}
});
}
});
}
private void initialWork() {
btnOnOff = (Button) findViewById(R.id.onOff);
btnDiscover = (Button) findViewById(R.id.discover);
btnSend = (Button) findViewById(R.id.sendButton);
listView = (ListView) findViewById(R.id.peerListView);
read_msg_box = (TextView) findViewById(R.id.readMsg);
ConnectoinStatus = (TextView) findViewById(R.id.connectionStatus);
writeMsg = (EditText) findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mMangaer = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mMangaer.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReciever(mMangaer,mChannel,this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers) ){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()]; //Size of deviceNameArray initialized
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()]; //Size of deviceArray initialized
int index = 0;
//assigning device name and device to 'deviceNameArray' and 'deviceArray'
for (WifiP2pDevice device: peerList.getDeviceList()){
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter= new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(MainActivity.this,"No Device Found!",Toast.LENGTH_LONG).show();
return;
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
WiFiDirectBroadcastReciever.java
package com.example.prototypewfp2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import static android.media.audiofx.Visualizer.STATE_ENABLED;
public class WiFiDirectBroadcastReciever extends BroadcastReceiver {
private WifiP2pManager mMangaer;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReciever(WifiP2pManager mMangaer, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mMangaer = mMangaer;
this.mActivity = mActivity;
this.mChannel = mChannel;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Wifi is Off", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mMangaer != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(context,"Acces Location (BroadcastRec) Not granted",Toast.LENGTH_SHORT).show();
}
mMangaer.requestPeers(mChannel, mActivity.peerListListener);
}
}
else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
}
else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
}
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/onOff"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="24dp"
android:layout_marginTop="47dp"
android:text="Wifi On/Off"
android:textSize="13dp" />
<Button
android:id="#+id/discover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/onOff"
android:layout_alignBottom="#+id/onOff"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:layout_marginLeft="0dp"
android:text="discover" />
<ListView
android:id="#+id/peerListView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/onOff"
android:layout_marginTop="25dp"
android:background="#android:color/holo_orange_light" />
<TextView
android:id="#+id/readMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/peerListView"
android:layout_marginTop="31dp"
android:text="Message"
android:textAlignment="center"
android:textSize="20sp"
android:textStyle="italic" />
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:ems="10"
android:inputType="textPersonName"
android:layout_toStartOf="#+id/sendButton" />
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Send" />
<TextView
android:id="#+id/connectionStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="Connection Status"
android:textAlignment="center"
android:textColor="#android:color/holo_blue_dark"
android:textSize="18sp"
android:textStyle="italic" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prototypewfp2p">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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/Theme.Prototypewfp2p">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
IDK why But you have to enable gps (Location) on both devices.
I have also tested with android version 8 device and android 10 device gps enabled Both are working perfectly fine.

Cannot resolve symbol 'file'

I am trying access the camera on an android device, so I tried some code from this site
I get this error: image at Imgur when I hover my mouse over 'file'. Take a look at the code below.
MainActivity.Java
package com.example.camera;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED){
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_image"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:onClick="takePicture"
android:text="Take a picture!"/>
</RelativeLayout>
android_manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera">
<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>
</application>
</manifest>
Sorry if there are some formatting errors, I am quite new to Stack Overflow. The code is some testing for a future project. If anyone could answer my question on this error, +1 to you. I would really appreciate the help :)
You need to declare file variable globally.
Like:
private Uri file;
In Java
A variable is a container that holds values that are used in a
Java program. To be able to use a variable it needs to be declared.
Declaring variables is normally the first thing that happens in any
program.

NullPointerException in Android app (Bundle?) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
In a class i am taking we have been learning some android app development and such, and i have managed to run into a problem that I, for the life of me, cannot figure out...
Basic background...
I get a nullpointerexception when I rotate the device... This error is located at Line 100 of QuizActivity.....
this Line is : mCheatButton.setOnClickListener(new View.OnClickListener() {//....
I suspect this has something to do with storing or retrieving information from the bundle...
Anyways here is the rest of The code....
Here is my quiz activity... Sorry for all the code blocks, I dont really know a better way to give you this information, or if you even need all of it.... But right now I just can figure out what is going on... so i have printed the error (stack trace? i think that is the right term...).. here as well...
03-02 09:49:28.858 7921-7921/com.example.ryan.ryans_quiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.ryans_quiz, PID: 7921
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ryan.ryans_quiz/com.example.ryan.ryans_quiz.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.ryan.ryans_quiz.QuizActivity.onCreate(QuizActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
QuizActivity
package com.example.ryan.ryans_quiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final int REQUEST_CODE_CHEAT = 0;
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true)
};
private int mCurrentIndex = 0;
private boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.trueButton);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.falseButton);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (ImageButton) findViewById(R.id.nextButton);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheatButton);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
Intent i = CheatActivity.newIntent(QuizActivity.this, answerIsTrue);
startActivityForResult(i, REQUEST_CODE_CHEAT);
}
});
updateQuestion();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null) {
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
}
My CheatActivity class
package com.example.ryan.ryans_quiz;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.TextView;
public class
CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
private static final String EXTRA_ANSWER_SHOWN =
"com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return i;
}
public static boolean wasAnswerShown(Intent result) {
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answer_text_view);
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.trueButton);
} else {
mAnswerTextView.setText(R.string.falseButton);
}
setAnswerShownResult(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int cx = mShowAnswer.getWidth() / 2;
int cy = mShowAnswer.getHeight() / 2;
float radius = mShowAnswer.getWidth();
Animator anim = ViewAnimationUtils
.createCircularReveal(mShowAnswer, cx, cy, radius, 0);
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
});
anim.start();
} else {
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
}
});
}
my Question Class
package com.example.ryan.ryans_quiz;
/**
* Created by Ryan on 1/20/2016.
*/
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int _textResId, boolean _answerTrue) {
mTextResId = _textResId;
mAnswerTrue = _answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
And finally my xml Files....
activity_cheat
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
tools:context="com.example.ryan.ryans_quiz.CheatActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
android:text="#string/warning_text"/>
<TextView
android:id="#+id/answer_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
tools:text="Answer"/>
<Button
android:id="#+id/show_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/show_answer_button"/>
</LinearLayout>
LandLayout - activity_quiz
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
vertical layout- activity_quiz
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
Strings..
<resources>
<string name="app_name">RyanHull_Quiz</string>
<string name="action_settings">Settings</string>
<string name="trueButton">True</string>
<string name="falseButton">False</string>
<string name="nextButton">Next</string>
<string name="previousButton">Previous</string>
<string name="cheat_button">Cheat!</string>
<string name="correct_toast">Correct! :)</string>
<string name="incorrect_toast">Incorrect! :(</string>"
<string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question_africa">The source of the Nile River is in Egypt.</string>
<string name="question_americas">The Amazon River is the longest river in the Americas.</string>
<string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string>
<string name="warning_text">Are you sure you want to do this??</string>
<string name="show_answer_button">Show Answer</string>
<string name="judgment_toast">Cheating is Wrong 8/</string>
<string name="title_activity_cheat">Cheat</string>
and finally manifest....
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.ryan.ryans_quiz"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".QuizActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".CheatActivity"
android:label="#string/title_activity_cheat"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
EDIT: its not a matter of me know what the exception is.. More of the matter of find where and why...
The lookup is failing for mCheatButton because you forgot to assign it an id in the landscape version of the activity_quiz.xml layout file.
When you then try to set a ClickListener on a null object that is where the NullPointerException is coming from.
when you rotate the device,the QuizActivity will destroy and then call onCreate,but your LandLayout file has no Button called 'cheatButton',so findViewById(R.id.cheatButton) will return null to mCheatButton, it can not call any method.
You haven't assigned any id to cheat button in LandLayout - activity_quiz
Change
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
to
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>

Admob Banner Ad is not displaying on Android App

I have a Android App. I need to integrate admob. I have included the following code but banner ad is not displaying in main layout please help regarding this your answers will be appreciated and it would be a great help. thank you.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:background="#drawable/hanumanji1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HanumanActivity" >
<Button
android:id="#+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:text="#string/pau"
android:textColor="#ffff00" />
<Button
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/pl"
android:textColor="#ffff00" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/de"
android:textColor="#ffff00" />
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ads:loadAdOnCreate="true"/>
</RelativeLayout>
MainActivity.java
package e.hanuman;
import e.hanuman.Constants;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import e.hanuman.R;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class HanumanActivity extends Activity implements OnClickListener{
Button play_button, pause_button, button1 ;
private AdView adView;
MediaPlayer player;
private int[] LEAVES = {
R.drawable.leaf_green,
R.drawable.leaf_red,
R.drawable.leaf_yellow,
R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hanuman);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
RelativeLayout layout = (RelativeLayout)findViewById(R.id.main_layout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest();
//adRequest.setTesting(true);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
getInit();
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 5000);
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
player.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
player.start();
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
player.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(HanumanActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
public void getInit() {
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
player = MediaPlayer.create(this, R.raw.hanu);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
player.start();
break;
case R.id.pause_button:
player.pause();
break;
case R.id.button1:
button1Click();
break;
}}
private void button1Click() {
// TODO Auto-generated method stub
startActivity(new Intent("e.hanuman.details"));
}
#Override
public void onBackPressed(){
if(player != null && player.isPlaying())
player.stop();
finish();
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
MANIFEST XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="e.hanuman"
android:versionCode="4"
android:versionName="4.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/hanuman"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:name="e.hanuman.Splash" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="e.hanuman.HanumanActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="details"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="e.hanuman.details" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
Change com.google.android.ads to com.google.android.gms.ads In your main activity and your manifest because you're using the old ads, use the .gms change your xml too, to the .gms adview.

Categories