Sudden error about not resolving some methods and symbols - java

I'm a beginner programmer and I'm working on an app where I want to have a Settings activity with 2 switch buttons (one to turn on/off notifications in status bar and one to turn on/off notification sound).Yesterday everything went fine with the compiling but today suddenly I got all these errors about not resolving some methods or symbols. What happened and how can I fix it?
In particular the errors where the following:
cannot resolve method: onCreate,setContentView,getSystemService, findViewById
cannot resolve symbol: OnCheckedChangeListener, simpleswitch1, simpleswitch2, arg0, view
Override: Annotations are not allowed here
onClick and onCheckedChanged do not work properly.
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new View.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onCheckedChanged(CompoundButton simpleswitch1, boolean isChecked) {
if (isChecked) {
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}});
public void onClick(View view) {
public void onCheckedChanged(CompoundButton simpleswitch2, boolean isChecked) {
if (isChecked){
notification.defaults |= Notification.DEFAULT_SOUND;
}}}}}
XML File
<?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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>

From you java you are placing methods inside other methods this is not possible in java
Also
Try setting listeners as such
// set default state on/off
simpleSwitch1.setChecked(false);
simpleSwitch2.setChecked(false);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
simpleSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
hope this helps, your java code was quite hard to understand.

Related

Crashing when switching on vibrate, silent and normal

My app crashing when I try to toggle phone modes. For example when I'm in ring mode end I try to switch on silent is crashing, but when I try to toggle vibrate is working fine. Exactly the same thing is happening when I try to change from vibrate to ring. Check status is working fine, there is not crash.
Here is the logcat line:
at com.example.lab3_1.MainActivity.onSilent(MainActivity.java:56)
That involved the code line:
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Here is the main:
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private AudioManager myAudioManager;
NotificationManager notificationManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new
Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
public void onMode(View v)
{
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_SILENT)
{
Toast.makeText(this,"Now in Silent Mode",Toast.LENGTH_LONG).show();
}
}
public void onRing(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
public void onSilent(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(this,"Now in silent Mode",Toast.LENGTH_LONG).show();
}
public void onVibrate(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
}
Here is the xml file:
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt1"
android:text="CURRENT MODE CHECK"
android:onClick="onMode"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt2"
android:text="RINGER MODE"
android:onClick="onRing"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt3"
android:text="SILENT MODE"
android:onClick="onSilent"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt4"
android:text="VIBRATE MODE"
android:onClick="onVibrate"/>
</LinearLayout>

Notifications don't show [duplicate]

This question already has an answer here:
Notifications don't appear
(1 answer)
Closed 2 years ago.
I'm new to programming and app development and I'm trying to develop an app that shows events and notifies the user when a new event is up.I'm trying to create a settings activity with 2 switch buttons, 1 for notifications on status bar and 1 for notification sound. When I turn on the switches, I don't get any notification nor sound.
How can I fix that?
JAVA FILE
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
if (simpleSwitch1.isChecked()){
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
/*
//API level 8
Notification myNotification8 = new Notification(R.drawable.ic_launcher, "this is ticker text 8", System.currentTimeMillis());
Intent intent2 = new Intent(MainActivity.this, SecActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0);
myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2);
manager.notify(11, myNotification8);
*/
}
});}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}
public void onClick(View v) {
simpleSwitch2 = (Switch) findViewById(R.id.simpleswitch2);
String statusSwitch2;
if (simpleSwitch2.isChecked())
notification.defaults |= Notification.DEFAULT_SOUND;
}}
XML FILE
<?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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
A couple of stuff here:
For switches, you probably want OnCheckedChangeListener, not
OnClickListener.
You want to set the OnCheckedChangeListener once in your onCreate() and check for the Switch's state
inside this listener:
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// show notification
} else {
// cancel notification
}
}
});`
// Similarly for switch2`

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

Adding a Icon to notification area in android app

O.K i have looked around this site and others and i see something similar to what i am wanting but yet it isn't what i am wanting...let me explain
i am learning to build an android app using eclipse that has a media player linked to my shoutcast server i am running, so far the apps works great but it doesn't have an icon on the top were the notification area is and when i go to a different app (a game) to play while leaving the music playing it minimizes the app .. thats fine but when i reopen the app it doesnt stop the mediaplayer infact if i play the player i will have 2 players running i will then have to force stop it using the task manager,, i know this can be done as i have apps on my phone that has icons and it will do what i am wanting
when i searched this site i found a link to youtube that has soemthing similar to what i am wanting
http://www.youtube.com/watch?v=e74z0_Z5QWI&feature=relmfu the code that is shown is as followed
import android.app.Activity;
public class StatusBar extends Activity implements OnclickListener{
NotificationManager nm;
#Override
Protected void onCreate(bundle savedInstance){
//TODO Auto-generated method Stub
super.oncreate(savedInstaceState);
setContentView(R.layout.statusbar);
Button stat = (Button)findViewById(R.id.bStatusBar);
stat.setOnClickListener(this);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void onClick(View v){
//TODO Auto-generated method Stub
Intent intent = new Intent(this, StatusBar.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
}
i have add this code to my MainActivity.java but it spits several errors to me that i have tried to fix using quickfix here is the script i currently have in my MainActivity.java file
package com.myapp.mytapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://link to url:8002";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(true);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(true);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
public void homepage (View view) {
goToUrl ( "http://myhomepage.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
here is what is in my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/black"
android:icon="#drawable/ic_launcher"
android:orientation="vertical"
startForeground()>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:clickable="true"
android:cursorVisible="true"
android:linksClickable="true"
android:onClick="homepage"
android:text="Home Page" />
</TableRow>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_play"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/play"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/play" >
</Button>
<Button
android:id="#+id/btn_pause"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/pause"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/pause" >
</Button>
<Button
android:id="#+id/btn_stop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/stop"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/stop" >
</Button>
</LinearLayout>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
</SeekBar>
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/scast" />
<TextView
android:id="#+id/Textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:hint="#string/version" >
</TextView>
</LinearLayout>
can someone tell me what i did wrong or can rewrite what i have and still keep everything working
Thanks in advance
Rob

Unfortunately (My App) Has Stopped Working

Okay, this happened when I created a simple ImageButton. I don't see what I'm doing wrong though... Here's my code:
(My Activity.Xml File):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tapbgh"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/level01"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/Score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/click0"
android:textColor="#FFFFFF"
android:textSize="16pt" />
<Chronometer
android:id="#+id/Timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:text="01:00"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/Tap"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.81"
android:background="#drawable/buttonbg" />
<Button
android:id="#+id/Menu"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Menu" />
<ImageButton
android:id="#+id/Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/resetbtn"
android:src="#drawable/resetbtn" />
</LinearLayout>
(My .Java File):
package my.first.app;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
//Click Events Below This Line
public class Tap_Game_Activity extends Activity {
private Button tapBtn;
private Button rstBtn;
int scr = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Menu = (Button) findViewById(R.id.Menu);
registerForContextMenu(Menu);
tapBtn = (Button) findViewById(R.id.Tap);
rstBtn = (Button) findViewById(R.id.Reset);
rstBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText("0");
scr = 0;
}
});
tapBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scr = scr + 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
}
});
}
// Options Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Menu");
menu.add(0, view.getId(), 0, "Resume");
menu.add(0, view.getId(), 0, "Quit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Invoke Context Function 1") {
contextFunction1(item.getItemId());
}
else if(item.getTitle()=="Invoke Context Function 2") {
contextFunction2(item.getItemId());
}
else {
return false;
}
return true;
}
public void contextFunction1(int id){
Toast.makeText(this, "function 1 invoked!", Toast.LENGTH_SHORT).show();
}
public void contextFunction2(int id){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Tap_Game_Activity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
I feel like it may be in this line:
rstBtn = (Button) findViewById(R.id.Reset);
But I still don't understand, any help would be great, thank you.
API tells me, that we can't cast ImageButton to Button. Try to declare rstBtn as an ImageButton and adjust the cast.
rstBtn = (Button) findViewById(R.id.Reset);
You are casting ImageButton to Button when ImageButton does not inherit from Button.
http://developer.android.com/reference/android/widget/ImageButton.html
BTW: Please choose a title that better describes your problem and include every error messages you get in your question.
private ImageButton rstBtn;
....
rstBtn = (ImageButton) findViewById(R.id.Reset);
rstBtn.setOnClickListener(........

Categories

Resources