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() {
...
Related
I have a problem in my code. I want to add items to a listview from another acivity onclickButton, but it only adds one item. And if I reapeat it, it only replaces the last added item. I can't figure out whats the problem some help please.
my code :
MainActivity:
package com.example.nasreddine.mtodubled; // project package
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity; //imports statements
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import android.content.DialogInterface;
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder alert;
public ArrayList<City> listItems;
ArrayAdapter adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState) { //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems=new ArrayList<>();
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);
//Displaying Data on ListView
cityListView=(ListView)findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a","b","","","","",""));
listItems.add(new City("v","c","","","","",""));
updateListView();
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
cityListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Delete Item from list");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
return true;
}
});
}
public void updateListView() {
Bundle bundle = getIntent().getExtras();
Intent intent=getIntent();
if (bundle != null) {
City a=new City(intent.getStringExtra("city"),intent.getStringExtra("country"),"/","/","/","/","/");
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivity(intent);
return (true);
}
return (super.onOptionsItemSelected(item));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
}
AddCity.java
package com.example.nasreddine.mtodubled;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton=(Button)findViewById(R.id.addButton);
final TextView cityAddText=(TextView)findViewById(R.id.cityAddText);
final TextView countryAddText=(TextView)findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent(AddCity.this,MainActivity.class);
intent.putExtra("city",city);
intent.putExtra("country",country);
startActivity(intent);
}
});
}
}
In your MainActivity.class start the AddCity.class using startActivityForResult().
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivityForResult(intent, requestCode); //ex: requestCode = 1
return (true);
}
return (super.onOptionsItemSelected(item));
}
After that in AddCity change add button click listener code with below:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent();
intent.putExtra("city",city);
intent.putExtra("country",country);
setResult(RESULT_OK, intent);
finish();
}
});
After that in MainActivity's onActivityResult() get data and add it to list. Also remove updatListView() method from MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
getActivity().invalidateOptionsMenu();
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
City a=new City(data.getStringExtra("city"),data.getStringExtra("country"),"/","/","/","/","/");
listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
}
You are restarting the MainActivity from AddCity Activity.
Rather than doing this, you need to start AddCity Activity, using method startActivityForResult().
And in AddCity Activity, rather than starting new MainActivity, you need to use setResult() method to send data to previous activity.
Also you need to override the onActivityResult method in MainActivity Class to owner the response from AddCity Activity.
Cheers!!!
Here is the code:
Class Main Activity,
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
AlertDialog.Builder alert;
public List<City> listItems;
ArrayAdapter<City> adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{ //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
//Displaying Data on ListView
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivityForResult(new Intent(MainActivity.this, AddCity.class), 1);
}
});
cityListView = (ListView) findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a", "b"));
listItems.add(new City("v", "c"));
updateListView();
}
public void updateListView()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
Class Add City,
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton = (Button) findViewById(R.id.addButton);
final TextView cityAddText = (TextView) findViewById(R.id.cityAddText);
final TextView countryAddText = (TextView) findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String city = cityAddText.getText().toString();
String country = countryAddText.getText().toString();
Intent intent = new Intent();
intent.putExtra("city", city);
intent.putExtra("country", country);
setResult(RESULT_OK, intent);
}
});
}
}
Hopefully, this will help you.
Cheers!!!
I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, 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);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i know it has been asked before for a different program but I am still getting error given below for my program
Thread [Thread-15956] (Suspended (exception ViewRootImpl$CalledFromWrongThreadException))
Please HELP!!
This is my MainActivity class
package a.example.na;
import java.util.Scanner;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static TextView inputtext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private BluetoothDevice mDevice;
private Button findBtn;
private String address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
findBtn.setEnabled(false);
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
inputtext = (TextView) findViewById(R.id.text);
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int pos,
long arg3) {
// Add the name and address to an array adapter to show in a ListView
String i = (String) adapterView.getItemAtPosition(pos);
B b=new B(inputtext);
b.start();
Scanner scanner = new Scanner(i);
if(scanner.hasNextLine()) {
address =scanner.nextLine();
}
mDevice = myBluetoothAdapter.getRemoteDevice(address);
scanner.close();
}
});
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add( device.getAddress()+ "\n" +device.getName() );
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#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
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
This is my separate Thread class
package com.bt;
import android.widget.TextView;
public class B extends Thread {
TextView inputtext;
public B(TextView x){
inputtext=x;
}
public void run(){
inputtext.setText("hero");
}
}
Your are touching the views(widgets) in the Non UI Thread.
public class B extends Thread {
TextView inputtext;
Activity activity;
public B(Activity activity, TextView x) {
inputtext = x;
this.activity = activity;
}
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
inputtext.setText("hero");
}
});
}
}
While starting the Thread
B b=new B(MainActivity.this, inputtext);
b.start();
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 am making a simple application, you put your name, click in a button, select a hobby and then it returns to the main layout your name and hobby together. I am having a problem when i click in the "Cancelar (Cancel)" button the application keeps getting a fatal error. What do you thing it could be?
MainActivity:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
TextView txtfinal;
String saludo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
txtfinal=(TextView)findViewById(R.id.textView1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivityForResult(intent, 1);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
if (resultCode == RESULT_CANCELED){
}
}
#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;
}
}
ActivitySaludo:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(RESULT_OK, iboton);
finish();
}
});
final Button BtnCancelar=(Button) findViewById(R.id.buttonCancelar);
BtnCancelar.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent iboton2 = new Intent();
iboton2 = null;
setResult(RESULT_CANCELED, iboton2);
finish();
}
});
}
}
if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
this is where the error is.. you need to remove the ; from the end of if statement and put { there and similarly end the block with }