Android programming on text views [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
can anybody help me ? I want to embed this block of code in my program but I dont know where to place it and I think it is an error for working with textViews in android
final TextView img1 = (TextView)findViewById(R.id.img1);
final TextView img2 = (TextView)findViewById(R.id.img2);
btnV.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
img1.setText(btnV.getText());
}
img1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
img1.setText("");
}
});

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView img1 = (TextView)findViewById(R.id.img1);
TextView img2 = (TextView)findViewById(R.id.img2);
final Button btnV = (Button)findViewById(R.id.btn1);
btnV.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
img1.setText(btnV.getText());
}
});
img1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
img1.setText("");
}
});
}
}
<TextView
android:id="#+id/img1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="img1" />
<TextView
android:id="#+id/img2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="img2" />
<Button
android:id="#+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btn1" />

use OnFocusChangeListener:
img1.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
img2.setText("");
}
});

Related

What gets called when the screen changes orientation? My app is restarting when I change orientations

I have built an app that is a simple question and answer game. A Question is displayed and you can select true or false, and then a toast appears to tell you if you got the question correct. You can then press a button to move to the next question. The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen? I have three classes. The first is the MainActivity which launches the quiz layout. The next is a Question class. The last is the QuizActivity Class. Here is the code:
MainActivity:
package com.example.geoquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
Question Class:
package com.example.geoquiz;
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int textResId, boolean answerTrue) {
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
QuizActivity Class:
package com.example.geoquiz;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { checkAnswer(true); }
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { checkAnswer(false); }
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
} // to close the entire class
I believe the code to update the question begins in the QuizActivity class. I think the issue is that the counter for which question to be displayed is being set back to 0, but I do not know where to set a breakpoint to check this. Whenever I set a breakpoint none of the UI is updated and I can therefore not test this.
I also have the XML file if you want to test this for yourself:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button" />
</LinearLayout>
<Button
android:id="#+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next_button" />
</LinearLayout>
The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen?
Your activity is destroyed and recreated as part of a configuration change. Consider using a ViewModel to hold your activity's state and be able to retain it across configuration changes.
You can use ViewModel or override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like as current question number and it will get passed in to onCreate() and also onRestoreInstanceState() where you would then extract the values.

How do I change my Activity's fragment container's background with a custom dialog with code?

Fairly new to Android and I am trying to do some background color changes. Basically I have a main activity that only has a FrameLayout in it's xml. When the activity is created it opens up a fragment for my program. I have a menu item that when clicked pops a dialog box with 3 seekbars(red, green, blue). I want to change the background color to whatever the seekbars position is. I have all the code finished for the seekbars and I know it works on a simple app I created. For reasons to me unknown my app fails when i try to open the dialog box. What is the proper way to set this up in the Main Activity? I want the user to be able to change the background color whenever they want. All my fragment layouts are transparent. This is the tutorial I have been working off of. http://android-er.blogspot.com/2009/08/change-background-color-by-seekbar.html Any advice would be great. I think my problem is I do not fully understand how to access my main_activity's FrameLayout from with-in my MainActivity java class.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#e3a153">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentView"></FrameLayout>
</LinearLayout>
Color_seekbar_selecter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change color"
/>
<SeekBar
android:id="#+id/mySeekingBar_R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_B"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
</LinearLayout>
menu_main.xml
<menu 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"
tools:context=".MainActivity">
<item android:id="#+id/menu_settings"
android:title="Green" />
<item android:id="#+id/menu_red"
android:title="Red" />
<item android:id="#+id/menu_blue"
android:title="Blue" />
<item android:id="#+id/menu_tan"
android:title="Tan" />
</menu>
MainActivity.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends ActionBarActivity {
//public CategoryFragment categoryFragment;
//public RecipeFragment recipeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
CategoryFragment categoryFragment = new CategoryFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentView, categoryFragment, "categoryFrag")
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_green:
}
return super.onOptionsItemSelected(item);
}
}
I have tried for hours to figure this out, but I just don't know where to put what.
This is the code from the example that I found in the link posted above.
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class SeekColorActivity extends Activity {
private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
updateBackground();
redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
updateBackground();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private void updateBackground()
{
seekR = redSeekBar.getProgress();
seekG = greenSeekBar.getProgress();
seekB = blueSeekBar.getProgress();
mScreen.setBackgroundColor(
0xff000000
+ seekR * 0x10000
+ seekG * 0x100
+ seekB
);
}
}
categoryFragment.java
package com.example.mikesgamerig.finalproject;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class CategoryFragment extends Fragment {
private ArrayList<String> categoryNameArrayList;
private ArrayAdapter<String> adapter;
private AlertDialog alertDialog;
private AlertDialog alertDialogDelete;
private EditText categoryEditText;
private String getCategoryName;
private List<Category> cats;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create view
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
//initialize all variables and widgets
inflater = getLayoutInflater(savedInstanceState);
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setView(inflater.inflate(R.layout.dialog_add_category, null));
alertDialogDelete = new AlertDialog.Builder(getActivity()).create();
alertDialogDelete.setView(inflater.inflate(R.layout.dialog_delete_category, null));
Button buttonAddCategory = (Button) rootView.findViewById(R.id.addCategoryButton);
ListView categoryListView = (ListView) rootView.findViewById(R.id.list);
//Array list to store names of categories
categoryNameArrayList = new ArrayList<String>();
//List of Category Objects
cats = Category.listAll(Category.class);
getCategoryNames();
//iterate through the CategoryList and attach to the ArrayList
//create adapter and fill the listView with all the name of categories
adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.label, categoryNameArrayList);
categoryListView.setAdapter(adapter);
//set OnClick listener for the add category Button.
// This calls another method that will open a custom dialog box
buttonAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisplayAddCategoryDialogBox();
}
});
//set an onItemLongClick listener for the ListView.
//First have to setLongClickable to true.
//the OnItemLongClick listener will call a method to open a custom Dialog to delete a category.
categoryListView.setLongClickable(true);
categoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
DeleteCategory(i);
return true;
}
});
//opens up a new fragment with a list of recipes for the specific category.
categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = categoryNameArrayList.get(i);
RecipeFragment fragment = new RecipeFragment();
fragment.SetTitleName(name);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragmentView, fragment)
.addToBackStack(null).commit();
}
});
return rootView;
}
//This method will Display a custom add category Dialog Box.
public void DisplayAddCategoryDialogBox(){
//Show the Dialog box to enter a new category name.
alertDialog.show();
categoryEditText = (EditText) alertDialog.findViewById(R.id.categoryEditText);
Button saveCategoryDialogBtn = (Button) alertDialog.findViewById(R.id.saveBtn);
Button cancelDialogButton = (Button) alertDialog.findViewById(R.id.cancelBtn);
saveCategoryDialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCategoryName = categoryEditText.getText().toString();
//Log.d("STRING VALUE:", getCategoryName);
Category test = new Category(getCategoryName);
test.save();
categoryNameArrayList.add(test.getName());
//Log.d("added Value: ", test.getName());
adapter.notifyDataSetChanged();
alertDialog.hide();
}
});
cancelDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.hide();
}
});
}
//this method will display a custom Delete Category Alert Dialog box.
public void DeleteCategory(final int i)
{
alertDialogDelete.show();
Button noBtn = (Button) alertDialogDelete.findViewById(R.id.noBtn);
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialogDelete.hide();
}
});
Button yesBtn = (Button) alertDialogDelete.findViewById(R.id.yesBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tempString = categoryNameArrayList.get(i);
//Log.d("VALUE OF STRING= ", tempString);
categoryNameArrayList.remove(i);
for (Category category : cats) {
String name = category.getName();
if (name.equals(tempString)) {
category.delete();
}
}
adapter.notifyDataSetChanged();
alertDialogDelete.hide();
}
});
}
//Filles the Array
public void getCategoryNames()
{
for(Category category : cats)
{
String name = category.getName();
categoryNameArrayList.add(name);
}
}
}

Songs not Playing on click

I have tried to create a simple android Media Player app in Eclipse which play songs from sdcard. All the songs are showing on the screen as a list but do not play when clicked.
Here is my MainActivity.java file :
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
class Mp3Filter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3"));
}
}
public class MainActivity extends ListActivity {
Button stop, play;
String SD_PATH = Environment.getExternalStorageDirectory().getPath();
List<String> songs = new ArrayList<String>();
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updatePlaylist();
stop = (Button) findViewById(R.id.button1);
play = (Button) findViewById(R.id.button2);
play.setVisibility(View.GONE);
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.pause();
if(mp.isPlaying()==false){
play.setText("Resume");
}
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
try{
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
if(mp.isPlaying()== true){
play.setText("Pause");
play.setVisibility(View.VISIBLE);
}
} catch(IOException e){
Log.v(getString(R.string.app_name),e.getMessage());
}
}
private void updatePlaylist() {
// TODO Auto-generated method stub
File home = new File(SD_PATH);
if(home.listFiles( new Mp3Filter()).length > 0){
for(File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_items,songs);
setListAdapter(songList);
}
}
#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);
}
}
Activity_Main.xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.studs.mediaplayer.MainActivity" >
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="50dp" >
</ListView>
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/android:list"
android:layout_alignParentBottom="true"
android:layout_marginLeft="23dp"
android:text="#string/pp" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/android:list"
android:layout_marginRight="52dp"
android:text="#string/st" />
</RelativeLayout>
and song_items.xml file :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</TextView>
Thanks in advance!
Your problem is in this line
mp.setDataSource(SD_PATH + songs.get(position));
songs.get(position) is only the file's name and since the file could be in some sub folder of your sdcard then you're not setting the correct data source..
Update
may be you can use a second list
List<String> songsPaths = new ArrayList<String>();
then update your method
private void updatePlaylist() {
// TODO Auto-generated method stub
File home = new File(SD_PATH);
if(home.listFiles( new Mp3Filter()).length > 0){
for(File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
songsPaths.add(file.getAbsolutePath());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_items,songs);
setListAdapter(songList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
try{
mp.reset();
mp.setDataSource(songsPaths.get(position));
mp.prepare();
mp.start();
if(mp.isPlaying()== true){
play.setText("Pause");
play.setVisibility(View.VISIBLE);
}
} catch(IOException e){
Log.v(getString(R.string.app_name),e.getMessage());
}
}

App Crashing on intent start with google maps

Java code for map activity
package com.schweigert.drinkingbuddy;
import android.app.Activity;
import android.os.Bundle;
public class BarMaps extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barmaps);
}
}
XML Code
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment" >
</fragment>
Java code that starts intent
maps.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
Intent openMap = new Intent("com.schweigert.drinkingbuddy.BarMaps");
startActivity(openMap);
}
});
When i am running this code on my emulator i have set up on my computer it brings up the "This app wont run unless you update Google Play services. But when i run it on a physical device it just times out and says that the app has stopped working.Why am i getting such a difference in errors between my emulator and physical device?
Edit:
package com.schweigert.drinkingbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class StartingPoint extends Activity {
double numDrinks;
int counter;
EditText standardDrinks;
Button bacIntent, maps, drinks;
TextView display;
Bundle testBundle;
#Override
protected void onCreate(Bundle testBundle) {
super.onCreate(testBundle);
setContentView(R.layout.activity_starting_point);
counter = 0;
bacIntent = (Button) findViewById(R.id.bacIntent);
maps = (Button) findViewById(R.id.Maps);
drinks = (Button) findViewById(R.id.drinks);
bacIntent.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){
try{
Intent openBac = new Intent("com.schweigert.drinkingbuddy.BloodAlcoholContent");
startActivity(openBac);
}
catch(Exception e)
{
display.setText("my d" + e);
}
}
});
maps.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Intent openMap = new Intent("com.schweigert.drinkingbuddy.MainActivity");
startActivity(openMap);
}
catch(Exception e){
display.setText("my d"+ e);
}
}
});
drinks.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Intent openDrinkMenu = new Intent("com.schweigert.drinkingbuddy.DrinkType");
startActivity(openDrinkMenu);
}
catch(Exception e){
display.setText("my d:" + e);
}
}
});
}
}
So i had a try catch that was interacting with a textview that didn't exist anymore and then i had my manifest set up incorrectly. Thanks for the help Shivan.

postInvalidate() not working with non-ui Thread

I am using a custom view to draw a game content and i use a button from xml layout to enable or disable the drawing of a specific content(rectangle) using separate thread.I managed to have the thread running but postInvalidate() method that i use is being ignored.I tried using setWillNotDraw(false) too.It isn't working.I've condensed my code,to be specific on which part of the code i have this problem.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frm"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.temp.Cview
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/bMineDetector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Lock" />
</RelativeLayout>
</FrameLayout>
And this is my MainActivity.java
package com.example.temp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button b;
Boolean lock=false;
Cview v;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new Cview(this,null);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
b=(Button) findViewById(R.id.bMineDetector);
lock=false;
b.setOnClickListener(this);
}
public void updateViewStart(){
v.onStart();
}
public void updateViewStop(){
v.onPause();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(v.isRunning==true)
v.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bMineDetector:
if(lock==false){
lock=true;
updateViewStart();
b.setText("UnLock");
}else{
lock=false;
updateViewStop();
b.setText("lock");
}
break;
}
}
}
In the above class i set a onClickListener that helps to start or stop a separate thread based on the state of the button.Here is my custom view where i handle touch events and also create this thread.
Cview.java
package com.example.temp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Cview extends View implements OnTouchListener,Runnable{
Boolean isRunning=false,isLockMode=false;
Context gameContext;
Thread myThread=null;
public Cview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
gameContext=context;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Log.d("INVALIDATE", "Invalidating");
isLockMode=((MainActivity)gameContext).lock;
if(isLockMode==true){
canvas.drawRect(100, 100, 300, 300, null);
//invalidate();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isLockMode=((MainActivity)gameContext).lock;
this.postInvalidate();
Log.d("THREAD", "isRunning="+isRunning+";;isLockMode="+isLockMode);
}
}
void onStart(){
isRunning=true;
myThread=new Thread(this);
myThread.start();
//Log.d("INVALIDATE", "onStart");
//postInvalidate();
}
void onPause(){
isRunning=false;
while(true){
try {
myThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
myThread=null;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return true;
}
}
Please anyone help me with this.I need the canvas to be redrawn once the run method is being executed.Ive been thinking about this for months and I'm new to programming too.So please guide me and suggest me if there is any other better method to do what i need.Thank you.
As explained in What is the difference between Android's invalidate() and postInvalidate() methods?, there might be some problems when postInvalidate is used from other threads.
I haven't tested this and it's not really nice, but it could help you (instead of this.postInvalidate();)
((MainActivity) gameContext).runOnUiThread(new Runnable() {
#Override
public void run() {
Cview.this.invalidate();
}
});
I just ran into the exact same issue.
The fix for me was to assign the custom view using
findViewById() in onCreate(), instead of calling the constructor.
Add
android:id="#+id/custom_view"
to your XML, and
v = (Cview) findViewById(R.id.custom_view);
to your onCreate() function (and remove the constructor call).
Do this after calling setContentView().
Android has gazillions of silent failure modes like this.

Categories