Android Async Task Progress Bar onProgressUpdate - android

I am a new programmer. I have seen lots of tutorials but can't understand what is wrong. I am trying to create a ProgressBar from an Async Task. However it always crashes my application.
Here is the "main" app:
package pt.flag.ensemble;
import java.util.Random;
import pt.flag.ensemble.task.AsyncTaskBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
public class Intervals extends Activity {
private static Intervals instance;
private Context context;
private String answer;
int right_question;
int wrong_question;
int randomInt2;
public ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intervals);
// initializing the sounds
final MediaPlayer sound1 = MediaPlayer.create(Intervals.this,
R.raw.maj2);
final MediaPlayer sound2 = MediaPlayer.create(Intervals.this,
R.raw.maj3);
final MediaPlayer sound3 = MediaPlayer.create(Intervals.this,
R.raw.maj4);
//ProgressBar
instance=this;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
progressBar.setProgress(0);
// Play Methods
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AsyncTaskBar().execute();
Play.setEnabled(false);
// generate random number
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
randomInt2 = randomInt;
// picking the right sound to play
switch (randomInt) {
case 1:
sound1.start();
answer = "M2";
break;
case 2:
sound2.start();
answer = "M3";
break;
case 3:
sound3.start();
answer = "P4";
break;
}
}
});
//Audio Repeat Methods
Button Repeat = (Button) findViewById(R.id.Repeat);
Repeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// picking the right sound to play
switch (randomInt2) {
case 1:
sound1.start();
new AsyncTaskBar().execute();
answer = "M2";
break;
case 2:
sound2.start();
new AsyncTaskBar().execute();
answer = "M3";
break;
case 3:
sound3.start();
new AsyncTaskBar().execute();
answer = "P4";
break;
}
}
});
}
//Answering Methods
public void buttonClicked2(View view) {
Button clickedButton = (Button) view;
if (clickedButton.getText().toString().equals(answer)) {
Toast.makeText(Intervals.this, "You are Right!", Toast.LENGTH_LONG)
.show();
right_question = right_question + 1;
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setEnabled(true);
// Passing results through
SharedPreferences sharedPref = getSharedPreferences(
"INTERVALRIGHTS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("SCORE", right_question);
editor.commit();
} else {
Toast.makeText(Intervals.this, "You are Wrong!", Toast.LENGTH_LONG)
.show();
wrong_question = wrong_question + 1;
// Passing results through
SharedPreferences sharedPref02 = getSharedPreferences(
"INTERVALWRONGS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref02.edit();
editor.putInt("SCORE02", wrong_question);
editor.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.intervals, 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.
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Intervals.this, IntervalResults.class);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public static Intervals getApp() { return instance; }
}
Here is the AsyncTask class
package pt.flag.eventapp.task;
import pt.flag.eventapp.Main;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
int progress_status;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Toast.makeText(Main.getApp(),"Invoke on PreExecute()", Toast.LENGTH_SHORT).show();
progress_status = 0 ;
//Main.getApp().txt_percentage.setText("downloading 0%");
}
#Override
protected Void doInBackground(Void... params) {
while (progress_status < 100){
progress_status +=2;
publishProgress(progress_status);
SystemClock.sleep(300);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//Main.getApp().progressBar.setProgress(values[0]);
//Main.getApp().txt_percentage.setText("downloading" + values[0] + "%");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Toast.makeText(Main.getApp(), "Invoke onPostExecute()", Toast.LENGTH_SHORT).show();
//Main.getApp().txt_percentage.setText("download complete");
}
}
Here is the Log:
08-10 20:38:11.081: E/AndroidRuntime(21441): FATAL EXCEPTION: main
08-10 20:38:11.081: E/AndroidRuntime(21441): java.lang.NullPointerException
08-10 20:38:11.081: E/AndroidRuntime(21441): at pt.flag.ensemble.task.AsyncTaskBar.onProgressUpdate(AsyncTaskBar.java:34)
08-10 20:38:11.081: E/AndroidRuntime(21441): at pt.flag.ensemble.task.AsyncTaskBar.onProgressUpdate(AsyncTaskBar.java:1)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.Looper.loop(Looper.java:156)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.app.ActivityThread.main(ActivityThread.java:4977)
08-10 20:38:11.081: E/AndroidRuntime(21441): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 20:38:11.081: E/AndroidRuntime(21441): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 20:38:11.081: E/AndroidRuntime(21441): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-10 20:38:11.081: E/AndroidRuntime(21441): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-10 20:38:11.081: E/AndroidRuntime(21441): at dalvik.system.NativeStart.main(Native Method)
If I am correct, the log seems to indicate an error in line 34 at the AsyncTask class, which is "Intervals.getApp().progressBar.setProgress(values[0]);" I just don't know why...
Also, here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/Play"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_marginTop="50dp"
android:layout_marginLeft="50dp" />
<Button
android:id="#+id/Repeat"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Repeat"
android:layout_marginTop ="50dp"
android:layout_toRightOf="#+id/Play"
android:layout_marginLeft="25dp" />
<ProgressBar
android:id="#+id/Progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test"
android:layout_marginTop="20dp"
android:layout_below="#+id/Play" />
<Button
android:id="#+id/Octave_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_marginLeft="5dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:text="#string/octave" />
<Button
android:id="#+id/min2_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Octave_Button"
android:text="#string/minor2" />
<Button
android:id="#+id/Maj2_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/min2_Button"
android:text="#string/major2" />
<Button
android:id="#+id/min3_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Maj2_Button"
android:text="#string/minor3" />
<Button
android:id="#+id/Maj3_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/min3_Button"
android:text="#string/major3" />
<Button
android:id="#+id/P4_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Maj3_Button"
android:text="#string/perfect4" />
<Button
android:id="#+id/A4_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Octave_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_marginLeft="5dp"
android:text="#string/tritone" />
<Button
android:id="#+id/P5_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/min2_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/A4_Button"
android:text="#string/perfect5" />
<Button
android:id="#+id/minor6_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Maj2_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/P5_Button"
android:text="#string/minor6" />
<Button
android:id="#+id/Major6_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/min3_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/minor6_Button"
android:text="#string/major6" />
<Button
android:id="#+id/minor7_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Maj3_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/Major6_Button"
android:text="#string/minor7" />
<Button
android:id="#+id/Major7_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/P4_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/minor7_Button"
android:text="#string/major7" />

I think it's better if you pass the progress bar as an argument to the AsyncTask:
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
progressBar.setProgress(0);
// Play Methods
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AsyncTaskBar task = new AsyncTaskBar();
task.setProgressBar(progressBar);
task.execute();
}
And then on your AsyncTask declare the setProgressBar method:
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
ProgressBar bar;
public void setProgressBar(ProgressBar bar) {
this.bar = bar;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (this.bar != null) {
bar.setProgress(values[0]);
}
}
You could do the same with the TextView you're trying to set.
In any case, since you mentioned you're new at this you may want to take a look at the Broadcast/Receiver pattern. Here's how it goes:
Start the async task without setting the progress bar or anything.
Define a BroadcastReceiver, instantiate one in your activity and register/unregister it accordingly.
Whenever there's a progress update on your async task just call sendBroadcast with the progress update as an intent extra. You may need to pass a context parameter when instantiating the AsyncTask.
The onHandleIntent method of your app's broadcast receiver (the one you instantiated on step 2) will run on the UI thread, making all those UI updates safe.
Sounds a bit overwhelming? It is at first, but here are the benefits:
It is much cleaner than passing UI objects to an AsyncTask.
You will learn a powerful Android pattern that will come in handy in other endeavours.
It will save you a lot of hassle (and exceptions) if you switch context or your app is low on memory.

Intervals.getApp().progressBar.setProgress(values[0]);
There are two possibilities for the NullPointerException in this line of code:
getApp() returns null
progressBar is null
In order to determine which is the cause, you need to split this into two separate lines:
Intervals intervals = Intervales.getApp();
intervals.progressBar.setProgress(values[0]);
Now set a breakpoint at the first line, step over it, and determine if intervals is null or not.

Related

change the colors of different buttons randomly at a specified time

I have 4 different buttons. I want to change the background of the buttons at a fixed time (say 1 sec i.e. one button changes its color for one sec then retains its previous color and then other button does the same and so on) in certain random pattern, and then the user will repeat this pattern. However I am unable to change the background of the buttons randomly. I know that a timer or handler will b used but I have no idea ho to use it. Can anyone post a example program that shows how to change the background of buttons randomly?
here is my 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:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<TextView
android:id="#+id/levelText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="50dp"
android:textColor="#FFFFFF"
android:text = "" />
<TextView
android:id="#+id/countDnText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="100dp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:text=""
/>
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button5"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="79dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button6"
android:layout_alignTop="#+id/button5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button7"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button8"
android:layout_alignTop="#+id/button7"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
`
here is my Activity:`
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class EasyGameActivity extends AppCompatActivity
{
private int counter;
private TextView text;
private boolean flag = false;
private Button button = null;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy_game);
startGame();
}
public void startGame()
{
counter = 3;
int temp;
final Random rand = new Random();
Handler handler = new Handler();
while(true)
{
BinaryTree binaryTree = new BinaryTree(counter);
for(int i = 0; i<counter; ++i)
{
temp = rand.nextInt(3);
// yellow color button...
if(temp == 0)
{
button = (Button) findViewById(R.id.button5);
button.setBackgroundColor(Color.YELLOW);
}
else if(temp == 1)
{
button = (Button) findViewById(R.id.button6);
button.setBackgroundColor(Color.BLUE);
}
else if(temp == 2)
{
button = (Button) findViewById(R.id.button7);
button.setBackgroundColor(Color.RED);
}
else if(temp == 3)
{
button = (Button) findViewById(R.id.button8);
button.setBackgroundColor(Color.GREEN);
}
//button.setBackgroundColor(Color.BLACK);
}
break;
}
}
}`
You could try something like this:
Button[] changingButtons = new Button[4];
changingButtons[0] = (Button)findViewById(R.id.button1_id);
changingButtons[1] = (Button)findViewById(R.id.button2_id);
changingButtons[2] = (Button)findViewById(R.id.button3_id);
changingButtons[3] = (Button)findViewById(R.id.button4_id);
You can then access the corresponding button in the array and change the background colour using changingButtons[<desired index>].setBackgroundResource(<color resource>)
To retain the previous color, you can use ColorDrawable previousBackground = (ColorDrawable)changingButtons[<desired index>].getBackground();
Then, for the "set time" part, use a timer, and do the colour switching in the TimerTask.
If you wish to use a TimerTask would look something like this inside the method calling it:
timer = new Timer();
timer.schedule(new MyTask(buttonNumber), numMilliseconds);
And then MyTask would be an extension class of TimeTask
class MyTask extends TimerTask
{
private int buttonId;
public MyTask(int buttonId)
{
super();
this.buttonId = buttonId;
}
public void run()
{
//Do your button alterations here
}
}
Here's a sample I made using the above code on Ideone
Hopefully this points you in the right direction!
For more information, check out these: Changing the background color programmatically, Getting the background color, Java Timer documentation
You can use Collections.shuffle(colorList);
List<String> colorList=new ArrayList<>();
colorList.add("#108E44");
colorList.add("#000000ff");
colorList.add("#108E44");
for() {
giveMeButtons(i).setBackgorundColor(Color.parseColor(colorList.get(i)));
}
And you must make other method. It will return random View button.

Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

Basically this app is supposed to ask for your name, with an option to save, which when click, an alert dialog pops up and asks 'are you sure?', when yes is clicked, it should say 'welcome + whatever name put'. my problem is that the app keeps shutting down before it says welcome. I declared the string as userName and ran it without any function to the string, and it just said 'welcome, null'.
but when i did
userName=editText.getText().toString();
the app shut down immediately. Please HELP I'm out of ideas.
the page which calls the welcome page works fine, but the welcome.java is the file with the issue.
public class Welcome extends Activity {
String userName;
final EditText editText=(EditText)findViewById(R.id.editText);
final TextView textView=(TextView)findViewById(R.id.textView);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final TextView textView=(TextView)findViewById(R.id.textView);
final EditText editText=(EditText)findViewById(R.id.editText);
userName=editText.getText().toString();
textView.setText(String.format("Welcome, %s.", userName));
}
}
The logcat is basically the title, giving an error to the following line:
userName=editText.getText().toString();
PS I've moved that line of code before and after onCreate and it still gave errors
My MainActivity.java is
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] menu={"User Preferences","Animation","Browser","Media","Take Picture"};
setListAdapter(new ArrayAdapter<String>(this,R.layout.activity_main,R.id.options, menu));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(MainActivity.this,userPreferences.class));
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}
#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);
}
}
My activity_main.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/ic_launcher_sf"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="2px">
</ImageView>
<TextView
android:id="#+id/options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/travel"
android:textSize="25sp"></TextView>
My welcome.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:textSize="30dp" />
my userpreferences.java
public class userPreferences extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpreferences);
Button save=(Button)findViewById(R.id.button);
save.setOnClickListener(new View.OnClickListener() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(userPreferences.this);
#Override
public void onClick(View v) {
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Are you sure you want to save?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(userPreferences.this,Welcome.class));
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
}
});
}
}
and my user preferences.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_weight="1"
android:hint="Enter Your Name"
android:textSize="20dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
The problem lies in both of these
final EditText editText=(EditText)findViewById(R.id.editText);
final TextView textView=(TextView)findViewById(R.id.textView);
Do not do findViewById without setContentView() called, or especially outside the methods. Make it:
private EditText editText;
private TextView textView;
And also:
inside your onCreate, you don't have to redeclare the views just do:
textView=(TextView)findViewById(R.id.textView);
editText=(EditText)findViewById(R.id.editText);
Plus: Add an EditText on your welcome.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="THIS IS AN EDITTEXT" />
The problem is that you have 2 different views in 2 different xml's called from one single activity. Which is why you get the nullpointerexception. so instead pass the context as an extra via an intent to the required activity and implement it in the findviewbyid method.

Android button returning to activity from layout

I can't find a way how to make it work. So here it goes:
Application starts and I press Option menu and it offers me "Settings" option, and when I click it, it goes to layout called "help.xml" which shows me some text ...And in that layout I created a button which must return me to my activity ( the window which is shown when app starts)
I tried making a back button works but I failed cause I need for user to wait 30 seconds until the next image switch , and by making back button works hw would exploit it..
Sorry for my English, it is not my native language ;)
//** Povratak= return **//
MainActivity
package com.example.ams;
import java.util.Random;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;
#Override
protected void onCreate(
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imgRandom);
btnRandom = (Button) findViewById(R.id.btnRandom);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
public void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btnRandom:
{
if (!btnRandom.isEnabled())
{
return;
}
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(45);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
btnRandom.setEnabled(false);
new CountDownTimer(30000, 1000) // Wait 30 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
btnRandom.setText("Pričekaj do sljedeće kartice: " + (millisUntilFinished / 1000));
}
#Override
public final void onFinish()
{
btnRandom.setText("PROMIJENI KARTICU !");
btnRandom.setEnabled(true);
}
}.start();
break;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
setContentView(R.layout.help);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void goBack(View v){
startActivity(new Intent(this, MainActivity.class));
}
#Override
public void onBackPressed() {
}
}
activity_main.xml
<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=".MainActivity"
android:background="#drawable/bgi"
>
<ImageView
android:id="#+id/imgRandom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
/>
<Button
android:id="#+id/btnRandom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imgRandom"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/imgRandom"
android:onClick="clickHandler"
android:text=" Promijeni karticu !"
android:textColor="#ffffff"
android:textSize="25dp" />
help.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:fillViewport="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:enabled="true"
android:freezesText="false"
android:overScrollMode="always"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
android:text="UVOD:Uz svaki scenario organizator moze odrediti da se koristi "AMS sustav" zbog realnijeg pristupa igri i viseg stupnja MILSIM-a. Organizator bira medice (ili kako se vec odredi) i oni moraju imati prilikom pocetka igre 46 kartica. />
</ScrollView>
<Button
android:id="#+id/button1"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:text="Povratak" />
So I want to "Povratak" button works, it needs to send user to lets called it "main menu" (go back)..
EDITED AND FIXED:
have another question, is there any way to activity remebers the counting, because when you enter the app you click button which random generates a image from drawable and it doesn't let user to press that button for 30 secs.. the problem now is that when you are waiting for counter go to 0 you can easily press option menu, click settings and click "povratak" ,which starts activity all over again and the counter losses its point because user can now again press button that generates image (and I dont want that):/
In your help.xml for your Povratak button, use:
android:onClick="goBack"
Then in your Help.java, use:
public void goBack(View v){
setContentView(R.layout.activity_main);
}
there is two way to fix that problem ,the first one is that you need to call the finish methode in your call back methode of the button like this :
in your help.xml file :
in your class Help.java implement your methode as follow :
public void Povratak(View v)
{
finish();
}
if that does not fix your problem you can start an intent to go to your main activity, you have to change the implimentation of your call back methode :
public void Povratak(View v){
Intent intent=new Intent(this,MainActivity.class);
startactivity(intent);
finish();
}
hope this help ,for more information about activity and intent you can see this tutoriel
click here

Exception in listener attached to multiple buttons in barcode app

Okay, So I am developing an in house barcode scanner for my company to use when we move computers and equipment. I am currently almost through setting up the Zxing Barcode Scanner Via Intent after some trial and error.
Here is what I'm trying to do.
Next to three EditText fields I have Three ImageButtons that when clicked, implement the BarcodeScanner, once scanned returns the value and inputs the value into the EditText field. I was able to do it successfully using one "listener" corresponding to one ImageButton. But after trying to use multiple Buttons with one listener, it calls the barcode scanner but crashes when trying to return the barcode value.
The Debugger shows the main Thread Suspended and I have to resume the debugger twice before the RuntimeException error appears in Logcat.
here's the error log from LogCat:
07-17 17:38:49.251: E/AndroidRuntime(30942):
java.lang.RuntimeException: Unable to resume activity
{com.fmi.inventory/com.fmi.inventory.MainActivity}:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=49374, result=-1, data=Intent {
act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }}
to activity {com.fmi.inventory/com.fmi.inventory.MainActivity}:
java.lang.NullPointerException
Here is my MainActivity:
package com.fmi.inventory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton button;
ImageButton button1;
ImageButton button2;
EditText editField;
Activity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
button = (ImageButton)findViewById(R.id.scanCubeID);
button1 = (ImageButton)findViewById(R.id.scanEmployeeID);
button2 = (ImageButton)findViewById(R.id.scanConfigID);
button.setOnClickListener(listener);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
}
public void setCubeClick(){
editField = (EditText)findViewById(R.id.editCubeID);
}
public void setEmployeeClick(){
editField = (EditText)findViewById(R.id.editEmployeeID);
}
public void setConfigClick(){
editField = (EditText)findViewById(R.id.editConfigID);
}
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.initiateScan();
}
};
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult = IntentIntegrator
.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
this.editField.setText(contents);
// this.elemQuery.setText(contents);
//this.resume = false;
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: "
+ format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
}
Here is my layout .xml for MainActivity
<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" >
<EditText
android:id="#+id/editCubeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/scanEmployeeID"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/scanCubeID"
android:ems="10"
android:hint="#string/edit_cubeid" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editEmployeeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/scanConfigID"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editCubeID"
android:layout_below="#+id/editCubeID"
android:ems="10"
android:hint="#string/edit_employeeid" />
<EditText
android:id="#+id/editConfigID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/scanConfigID"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editEmployeeID"
android:layout_below="#+id/editEmployeeID"
android:ems="10"
android:hint="#string/edit_configid" />
<ImageButton
android:id="#+id/scanCubeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_alignParentTop="true"
android:src="#drawable/ic_action_scan"
android:onClick="onClick" />
<ImageButton
android:id="#+id/scanEmployeeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_below="#+id/scanCubeID"
android:src="#drawable/ic_action_scan"
android:onClick="onClick" />
<ImageButton
android:id="#+id/scanConfigID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_below="#+id/scanEmployeeID"
android:src="#drawable/ic_action_scan"
android:onClick="onClick" />
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editConfigID"
android:text="#string/button_continue" />
</RelativeLayout>
When your Activity come in onActivityResult after scanning.You are accessing editField but it is NULL.
as you never Initialized it..
You are Initializing them in setCubeClick, setEmployeeClick or setConfigClick,
But I am affraid they never called..Try to Initialize them in OnCreat

Using OnClickListener with multiple ImageButtons?

I'm trying to pull data from a barcode with plain text via zxing using their ScannerViaIntent source code. It works perfectly fine when I set up the code for a single ImageButton but when i set up the other two buttons I receive this error when returning the result from the Barcode Scanner.
Error:
07-18 14:16:00.080: E/AndroidRuntime(9004): java.lang.RuntimeException: Unable to resume activity {com.fmi.inventory/com.fmi.inventory.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=49374, result=0, data=null} to activity {com.fmi.inventory/com.fmi.inventory.MainActivity}: java.lang.NullPointerException
07-18 14:16:00.080: E/AndroidRuntime(9004): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=49374, result=0, data=null} to activity {com.fmi.inventory/com.fmi.inventory.MainActivity}: java.lang.NullPointerException
07-18 14:16:00.080: E/AndroidRuntime(9004): at com.fmi.inventory.MainActivity.onActivityResult(MainActivity.java:70)
Code:
package com.fmi.inventory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton button;
ImageButton button1;
ImageButton button2;
EditText editField;
Activity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
button = (ImageButton)findViewById(R.id.scanCubeID);
button1 = (ImageButton)findViewById(R.id.scanEmployeeID);
button2 = (ImageButton)findViewById(R.id.scanConfigID);
button.setOnClickListener(listener);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
}
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
switch (v.getId()){
case (R.id.scanCubeID):
editField = (EditText)findViewById(R.id.editCubeID);
integrator.initiateScan();
case (R.id.scanEmployeeID):
editField = (EditText)findViewById(R.id.editEmployeeID);
integrator.initiateScan();
case (R.id.scanConfigID):
editField = (EditText)findViewById(R.id.editConfigID);
integrator.initiateScan();
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String barcode = scanResult.getContents();
this.editField.setText(barcode);
}
// else continue with any other code you need in the method
}
}
Layout:
<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" >
<EditText
android:id="#+id/editCubeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/scanEmployeeID"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/scanCubeID"
android:ems="10"
android:hint="#string/edit_cubeid" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editEmployeeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/scanConfigID"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editCubeID"
android:layout_below="#+id/editCubeID"
android:ems="10"
android:hint="#string/edit_employeeid" />
<EditText
android:id="#+id/editConfigID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/scanConfigID"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/editEmployeeID"
android:layout_below="#+id/editEmployeeID"
android:ems="10"
android:hint="#string/edit_configid" />
<ImageButton
android:id="#+id/scanCubeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_alignParentTop="true"
android:src="#drawable/ic_action_scan"/>
<ImageButton
android:id="#+id/scanEmployeeID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_below="#+id/scanCubeID"
android:src="#drawable/ic_action_scan"/>
<ImageButton
android:id="#+id/scanConfigID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/desc"
android:layout_below="#+id/scanEmployeeID"
android:src="#drawable/ic_action_scan"/>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editConfigID"
android:text="#string/button_continue" />
</RelativeLayout>
add break for cases in switch as :
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
switch (v.getId()){
case (R.id.scanCubeID):
editField = (EditText)findViewById(R.id.editCubeID);
integrator.initiateScan();
break ; // add here
case (R.id.scanEmployeeID):
editField = (EditText)findViewById(R.id.editEmployeeID);
integrator.initiateScan();
break ;// add here
case (R.id.scanConfigID):
editField = (EditText)findViewById(R.id.editConfigID);
integrator.initiateScan();
break ; // add here
}
}
};

Categories

Resources