Hopefully this hasn't been asked.
In building an app and having successfully opened a new activity from the main activity, when the back button is pressed the app exits instead of returning to the main activity.
Here is the code for the activity that gets called from the main one.
package com.austinrhodes.simplesounds;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
public class About extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the main activity
package com.austinrhodes.simplesounds;
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Launch extends Activity {
int size = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//inflate view from XML
setContentView(R.layout.activity_launch);
createTvArray();
}
private void createTvArray() {
//create array of text views to be added to main view
TextView[] tv = new TextView[size];
//create a temporary text view
TextView temp;
for (int i = 0; i < size; i++)
{
//make a new text view object for each of the alarms
temp = new TextView(this);
temp.setText("Alarm: " + i); //arbitrary task
//get instance of Linear Layout
LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linearAlarm);
// add the textview to the linearlayout
myLinearLayout.addView(temp);
tv[i] = temp;
}
}
private void openSettings(){
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
finish();
}
private void openAbout(){
Intent intent = new Intent(this, About.class);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_launch, menu);
return true;
}
public boolean onCreateOptionsMenu1(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_launch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
openSettings();
return true;
case R.id.new_alarm:
DialogFragment newFragment = new AddAlarm();
newFragment.show(getFragmentManager(), "add_alarm");
return true;
case R.id.about:
openAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The concerned parties xml snippet
<activity android:name="com.austinrhodes.simplesounds.About" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.austinrhodes.simplesounds.Launch" />
</activity>
try this
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
CurrentClass.this.finish();
Intent i = new Intent(CurrentClass.this, MainActivity.class);
startActivity(i);
return true;
default:
return false;
}
Related
I am trying to use the following code
public int id=GeneralPreferenceFragment.getView().getParent().getId();
inside SettingAvtivity/MainActivity .
but it shows following error
Non-static method 'getView()' can not be referenced from a static Context
please help me resolving this issue
following is the method used
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
int id = prefFragment.getView().getParent().getId();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.layout_1id,fragment);
ft.remove(fragment1);
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
if i use an instance of General preferenceFragment then it shows
Cannot resolve getId();
code for header that links fragment-pref_header.xml
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<!-- These settings headers are only used on tablets. -->
<header
android:fragment="com.example.amit.check1.SettingsActivity$GeneralPreferenceFragment"
android:icon="#drawable/ic_info_black_24dp"
android:title="#string/pref_header_general"
android:id="#+id/id3"/>
<header
android:fragment="com.example.amit.check1.SettingsActivity$NotificationPreferenceFragment"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/pref_header_notifications" />
<header android:fragment="com.example.amit.check1.SettingsActivity$DataSyncPreferenceFragment"
android:icon="#drawable/ic_sync_black_24dp"
android:title="#string/pref_header_data_sync" />
</preference-headers>
SettingActivity.java
package com.example.amit.check1;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.telecom.Call;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
//private int mcontainerid;
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// int id=GeneralPreferenceFragment.getView().getParent().getId();
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
Preference preference = findPreference("launchFragment");
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// launch fragment
// addPreferencesFromResource(R.xml.pref_notification);
// Toast.makeText(getActivity(),"hellp",Toast.LENGTH_SHORT).show();
return false;
}
});
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// int id = prefFragment.getView().getId();
//String st=Integer.toString(id);
//Toast.makeText(SettingsActivity.this,st,Toast.LENGTH_SHORT).show();
// int id = frag1.getView().getParent().getId();
//ViewGroup vg = (ViewGroup) findViewById(id);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
//ft.add(1234,fragment,"f1");
//int id=fragment.getId();
//String s1=Integer.toString(id);
// Toast.makeText(SettingsActivity.this,s1,Toast.LENGTH_SHORT).show();
// ft.add(R.id.layout_1id,fragment);
//ft.add() will add fragment in previous fragment to
// the previous fragment
// ft.replace(R.id.layout_1id,fragment);
// ft.hide(fragment1);
//ft.hide() is used to hide an fragment;
// ft.detach(fragment1);
//detach method removes the fragment from UI.but it can be reused with the help
//of attach method.
//Toast.makeText(SettingsActivity.this,"removed frag1",Toast.LENGTH_SHORT).show();
//ft.show(fragment);
ft.remove(fragment1);
//remove method removes the fragment from UI;you can reuse fragment again,for reusing
//again you would have to use add method
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
You need to call method getView() from instance of you class GeneralPreferenceFragment. I.e:
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// ... some business logic
public int id = prefFragment.getView().getParent().getId();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have been looking around for the answer but no luck on this. to resume
the id of my button is correct
Activity names are correct, but for some reason the Bundle is returning null and crashing my App, This is my Main Activity, please help.
Check the OnClick Listener I think I am using the correct form
Main Activity
package com.example.carlos.application1;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
int status = 0;
Button hp_1, HP2, fo, previous, home, next,MZ,Control,show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
hp_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = 1;
Bundle bundle = new Bundle();
bundle.putInt("status", status);
Intent intent = new Intent(MainActivity.this, DisplayValues.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
you haven't assigned anything to hp_1 so its value is NULL and that is the problem. You need to do the following:
hp_1 = (Button) findViewById(...);
hp_1.setOnClickListener(new View.OnClickListener() {
...
enter code hereThis is my First Activity::> I need:
1) select an option
2) click send an image (from drawable) should go to the second activity but it does not only from 2nd to 1st works fine all my xml and manifest files are correct (I double checked)
package com.example.damianlopez.myassignment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button toBob;
private ImageView burgerImage;
private RadioGroup radioGroupChoice;
private RadioButton radBurger;
private RadioButton radScare;
private RadioButton radSick;
private final int MY_SELECTION = 111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_main);
//get radio Buttons
//radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
radBurger = (RadioButton)findViewById(R.id.radBurger);
radScare = (RadioButton)findViewById(R.id.radScare);
radSick = (RadioButton)findViewById(R.id.radSick);
//display app icon
ActionBar ab = getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setIcon(R.mipmap.ic_launcher);
//getting Intent
Intent getIntent = getIntent();
Bundle myBundle2 = getIntent.getExtras();
setResult(Activity.RESULT_OK, getIntent);
//
}catch(Exception e ){
}
}//End onCreate()
public void onClickButton(View v){
try {
//get radio gruop id's
radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
int mySelection = radioGroupChoice.getCheckedRadioButtonId();
if(radioGroupChoice.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
}else {
//creating new Intent
Intent msgToBob = new Intent(MainActivity.this, Main22Activity.class);
Bundle myBundle = new Bundle();
myBundle.putInt("imageChoice", mySelection);
msgToBob.putExtras(myBundle);
startActivityForResult(msgToBob, MY_SELECTION);
}
}catch(Exception e ){
}
}//End of onClick()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent myData) {
super.onActivityResult(requestCode, resultCode, myData);
Log.i("OnActivityResult() call", "***********");
radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
int selected = radioGroupChoice.getCheckedRadioButtonId();
//get Images
burgerImage = (ImageView) findViewById(R.id.pumpkin_burger);
if(radioGroupChoice.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
}
else {
switch (requestCode) {
case MY_SELECTION: {
if (resultCode == Activity.RESULT_OK) {
if (radBurger.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_burger);
} else if (radScare.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_scared);
} else if (radSick.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_sick);
};
}
break;
}//end case
}//end switch
}//end else if
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();``
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Second Activity===>
package com.example.damianlopez.myassignment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Main22Activity extends AppCompatActivity {
private RadioGroup radioGroupChoice2;
private RadioButton radBurger;
private RadioButton radScare;
private RadioButton radSick;
private Button toAlice;
private ImageView currentImage;
private ImageView scareImage;
private ImageView sickImage;
private final int MY_SELECTION2 = 222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
//display app icon
ActionBar ab = getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setIcon(R.mipmap.ic_launcher);
//Buttons
radioGroupChoice2 = (RadioGroup)findViewById(R.id.radGroupChoice);
//toAlice = (Button) findViewById(R.id.sndToAlice);
//get the intent called
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
myLocalIntent.putExtras(myBundle);
setResult(Activity.RESULT_OK, myLocalIntent);
}
public void onClickButton2(View v){
try {
radioGroupChoice2 = (RadioGroup) findViewById(R.id.radGroupChoice);
if (radioGroupChoice2.getCheckedRadioButtonId() == -1) {
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
} else {
Intent myIntent2 = new Intent();
Bundle myBundle2 = new Bundle();
int myImage = radioGroupChoice2.getCheckedRadioButtonId();
myBundle2.putInt("selectedImage", myImage);
myIntent2.putExtras(myBundle2);
setResult(Activity.RESULT_OK, myIntent2);
}
}catch(Exception e) {
}
finish();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main22, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am trying out below code
here is the MainActivity.java
import java.io.File;
import java.util.ArrayList;
import javax.crypto.spec.PSource;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterViewFlipper;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvPlaylist);
final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
items = new String[mySongs.size () ];
for (int i = 0; i < mySongs.size(); i++) {
//toast(mySongs.get(i).getName().toString());
items[i] = mySongs.get(i).getName().toString();
}
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,R.id.textView1,items);
lv.setAdapter(adp);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(), player.class).putExtra("pos", position).putExtra("songlist",mySongs));
}
});
}
public ArrayList<File> findSongs(File root){
ArrayList al = new ArrayList<File>();
File[] files = root.listFiles();
for(File singleFile : files){
if (singleFile.isDirectory()&& !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
}
else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
al.add(singleFile);
}
}
}
return al;
}
public void toast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
above code gives me a list of mp3 files when we click on one of the songs it takes to player.ja and songs are played
and
player.java
import java.io.File;
import java.util.ArrayList;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class player extends ActionBarActivity implements View.OnClickListener{
static MediaPlayer mp;
ArrayList<File> mySongs;
int position;
Uri u;
SeekBar sb;
Button btPv, btFB,btplay,btFF, btNxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btFB = (Button) findViewById(R.id.btFB);
btPv = (Button) findViewById(R.id.btPv);
btplay = (Button) findViewById(R.id.btplay);
btFF = (Button) findViewById(R.id.btFF);
btNxt = (Button) findViewById(R.id.btNxt);
btFB.setOnClickListener(this) ;
btPv.setOnClickListener(this);
btplay.setOnClickListener(this);
btFF.setOnClickListener(this);
btNxt.setOnClickListener(this);
//
if(mp != null)
{
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u).start();
mp.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v)
{
int id = v.getId();
switch (id) {
case R.id.btplay:
if(mp.isPlaying())
{btplay.setText("play");
mp.pause();
}
else
{ btplay.setText("play");
mp.start();
}
break;
case R.id.btFF:
mp.seekTo(mp.getCurrentPosition()+ 5000);
break;
case R.id.btFB:
mp.seekTo(mp.getCurrentPosition()- 5000);
break;
case R.id.btNxt:
mp.stop();
mp.release();
position = (position+1)%mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
break;
case R.id.btPv :
mp.stop();
mp.release();
// Important
position = (position-1<0) ? mySongs.size()-1: position-1;
/*if(position-1 < 0)
{
position = mySongs.size()-1;
}
else
{
position= position-1;
}*/
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
default:
break;
}
}
}
While the above code works perfectly fine for few songs which are mp3 but it does not work for other songs which are also mp3 . I have tried this on an actual device the app would just crash if the song has some problem
the mp3 files which give me problems work perfectly on other media players and even the default android media player
What exactly could be the issue?
you need to call mediaPlayer.prepare() or mediaPlayer.prepareAsync() before you call , mediaPlayer.start(), also if the application crash, post your log so we can know the problem.
I have an app in which I have a WebView where I display some websites.
I want create a Share button in Menu.I've tried a lot of code.
What should I write here ?
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
MainActivity.java
package com.kefelon.goldplak;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends ActionBarActivity {
WebView webview;
private ShareActionProvider mShareActionProvider;
ProgressBar loadingProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.goldplak.com");
webview.setWebViewClient(new WebViewClient() {
});
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
webview.setWebChromeClient(new WebChromeClient() {
// this will be called on page loading progress
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
loadingProgressBar.setProgress(newProgress);
//loadingTitle.setProgress(newProgress);
// hide the progress bar if the loading is complete
if (newProgress == 100) {
loadingProgressBar.setVisibility(View.GONE);
} else{
loadingProgressBar.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onBackPressed()
{
if(webview.canGoBack()){
webview.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Çıkış")
.setMessage("Uygulamadan çıkmak istediğinize emin misiniz?")
.setPositiveButton("Evet", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Hayır", null)
.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_about:
action_aboutMenuItem();
break;
case R.id.action_share:
action_shareMenuItem();
break;
case R.id.action_settings:
action_settingsMenuItem();
break;
}
return true;
}
private void action_aboutMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Hakkımızda")
.setMessage("Gold Plak olarak müzik sektörü ile ilgili müşteri odaklı kişisel ve kurumsal hizmet veren, dinamik, güler yüzlü, yaratıcı kadromuzla müşterilerimizin beklentilerini karşılamak için kesintisiz hizmet vermekteyiz.\n" +
"\n" +
"Bu şekilde müşterilerimizin plak ve dj ekipmanlarından yararlanmalarını sağlayarak taleplerini karşılayabilmek. Hedefimiz, yeni çıkan tüm ürünleri sunmak, maksimum düzeyde müşteri memnuniyetini sağlamak..")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
private void action_settingsMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Versiyon")
.setMessage("Gold Plak v1.1")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
You may need to create an xml file inside res>menu directory of your project for a share menu,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/share"
android:icon="#drawable/ic_action_share" // share button icon.
android:showAsAction="always"
android:title="#string/action_share">
</item>
</menu>
In your java file,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.desc_xml, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.share) {
shareNews();
}
return super.onOptionsItemSelected(item);
}
and here is the share news method,
private void shareNews() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Put Data Here");
startActivity(Intent.createChooser(shareIntent,getString("How do you want to share")));
}
This question has already been answer but anyway, this is a working solution :
in your fragment/activity:
private ShareActionProvider mShareActionProvider;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.deal_detail, menu);
// Locate MenuItem with ShareActionProviderr
MenuItem item = menu.findItem(R.id.action_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
mShareActionProvider.setShareIntent(getShareIntent());
}
// Create the share intent
private Intent getShareIntent() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "yoursubject");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "yourtext);
return sharingIntent;
}