Trouble loading random image on button press - java

What i'm trying to do is just simply have the button load an image at random. However, the button doesn't seem to be working. When i first load the activity there it works fine and there is a random image....But when i press the button it's not loading another like i need it to. Any idea what i have wrong here? It looks fine to me :/
package com.my.package;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
public class Randomimage extends Activity implements OnClickListener{
private Integer [] mImageIds = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
};
private static final Random rgenerator = new Random();
private ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv = (ImageView) findViewById(R.id.imageviewyeah);
iv.setImageResource(q);
View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next_image_button:
iv.setImageResource(rgenerator.nextInt(mImageIds.length));
break;
}
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu3, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
startActivity(new Intent(this, Main.class));
return true;
case R.id.startnhie:
startActivity(new Intent(this, startnhie.class));
return true;
}
return false;
}
}

In your button press handling code, change
iv.setImageResource(rgenerator.nextInt(mImageIds.length));
to
iv.setImageResource(mImageIds[rgenerator.nextInt(mImageIds.length)]);

Related

android app, Java - Overflow Menu Error and it's not displaying in the action bar

I did not expect an error to come up but the 3-dot ActionBar menu is not displaying and I am getting an unexpected error. I am not sure where I went wrong in my code.
Please help,
thanks in advance!
MainActivity.java
package com.example.it5.foothillers;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
Button button2;
Button button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Display app icon in the ActionBar
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_launcher);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(this);
}
private void buttonClick() {
startActivity(new Intent("it5.foothillers.news"));
}
private void button2Click() {
startActivity(new Intent("it5.foothillers.sports"));
}
private void button3Click() {
startActivity(new Intent("it5.foothillers.events"));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
buttonClick();
break;
case R.id.button2:
button2Click();
break;
case R.id.button3:
button3Click();
break;
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(MenuItem item) {
int id = item.getItemId();
}
}
You have 3 onCreateOptionsMenu methods. Remove the last 2, you only need the first one with inflater. Also, Override the onOptionsItemSelected method to control the actions.

Android: unable to create Media Player (using pls URL)

I'm trying to create an app that plays an internet radio stream from a .pls file. I know that the Android Media Player can't read .pls files, so I read it beforehand and obtained the URL that is stored in the .pls file. That's what's in the R.String.audio_stream variable I pass to setDataSource(). However, when I run my code on the simulator, it fails when I try to start the media player. LogCat returns the error message, "Unable to create media player." Does anyone know what might be the problem?
Here's my code:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Button mStartButton;
private Button mStopButton;
boolean isPlaying = false;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = new MediaPlayer();
mStartButton = (Button)findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isPlaying){
//do nothing
}else{
isPlaying = true;
try{
mp.setDataSource(getString(R.string.audio_stream));
mp.prepare();
mp.start();
}catch(IOException e){
Log.e(TAG, "prepare() failed.");
}
}
}
});
mStopButton = (Button)findViewById(R.id.stop_button);
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isPlaying){
//do nothing
}else{
isPlaying = false;
mp.release();
}
}
});
}
#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);
}
}
Its easy. You must use before "setDataSource":
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

How to create a Login task in OnClickListener?

How to create a task with OnClickListener???
I Tryed with two methods (AsyncTask & Runnable/Thread):
I have test the AsyncTask Method:
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask(getActivity()).execute("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
}
});
return rootView;
}
}
}
class LoginTask extends AsyncTask<String, Integer, Long> {
private FragmentActivity activity;
public LoginTask(FragmentActivity activity) {
this.activity = activity;
}
protected Long doInBackground(String... urls) {
try{
URL oracle = new URL(urls[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(activity, "Failed", Toast.LENGTH_LONG).show();
}
return (long) 0;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
and i have tested a Runnable Method
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Runnable run = new Runnable() {
#Override
public void run() {
try{
URL oracle = new URL("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(getActivity(), "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
};
Thread t = new Thread(run);
t.start();
}
});
return rootView;
}
}
}
but this two Methods dosent works.
I noticed, that you called Toast.makeText(...).show() from doInBackground(). It will not work. I wish I could write this as a comment, but I don't have enough reputation...
Also, URLEncoder.encode() is deprecated. Try encode with encoding as the second argument.
And in the end, usually, network operations are implemented using HttpUrlConnection or DefaultHttpClient (the first is preferable). Here you can find a code snippet.

Android: Share content pop up window

I found this code to create a share window:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class AndroidShareActionProviderActivity extends Activity {
private ShareActionProvider myShareActionProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.completed);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
myShareActionProvider = (ShareActionProvider)item.getActionProvider();
myShareActionProvider.setShareHistoryFileName(
ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
myShareActionProvider.setShareIntent(createShareIntent());
return true;
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
"http://www.example.com/");
return shareIntent;
}
}
My question is, is it possible to make this share window open when an ImageButton outside the actionbar is clicked instead and if possible how to do that?
yes and not so difficult either. what you need to do is lauch the intent in your onclick. since that method returns the view u want it will be something like this
this.YOURIMAGEBUTTON.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(createShareIntent()));
}
});

How do I use setResult when returning from an activity?

I need help, I am making a simple application, and I donĀ“t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
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.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.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);
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);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#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 com.example.holaamigos.R.string;
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 {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
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(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.

Categories