Android - Toast button not appearing - java

After reading about Android's Toast class, I had to try it out.
I added a button to my layout, followed the instructions on this page, and added an OnClickListener to my button that would call the toast.
The problem now is that when I debug the app, the button doesn't appear on the view.
Do I have something where it's not supposed to be? (Additional information available upon request)
Code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relLayout"
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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button" />
</RelativeLayout>
MainActivity.java
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
Context context = getApplicationContext();
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(context, text, duration).show();
}
}

try this :
btnToast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast msg = Toast.makeText(MainActivity.this, text, duration );
msg.show();

Just guessing here, but I'd start removing those paddings in your RelativeLayout. You may be running the app in a device in which values of
#dimen/activity_vertical_margin
and/or
#dimen/activity_horizontal_margin
are 'moving' your button out of the screen. You can also try aligning the button in the center of the view.-
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />

You must create your context inside onCreate() method:
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
Context context = getApplicationContext();
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(context, text, duration).show();
}
}

You can't use the application context for UI stuff, like creating dialogs, toasts or launching activities. Just use the activity as a context instead.
Different contexts in Android, and what they can and can't be used for.

I got it to work by removing the context and duration variables altogether and setting them manually inside my Toast method.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_SHORT).show();
}
}

This should work:
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(this);
}
});
}
private void toastMe(Context context) {
Toast.makeText(context, text, duration).show();
}
}

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.

Programmatically changing background

I have this code that changes the background when you click a button however, I want to change the background every 10 seconds, and I want to switch between files img1.png, img2.png and img3.png and when the cycle is completed start all over again. Thanks in advance.
Here is the code:
In 'MainActivity.java'
package lucas.app_2001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout=(LinearLayout)findViewById(R.id.myLayout);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mainLayout.setBackgroundResource(R.drawable.yellowgradient);
}
});
}
}
'MainActivity.xml':
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="71dp"
android:text="Shout!" />
</LinearLayout>
You can do this way:
private Handler mHandler;
private Runnable mRunnable;
private int i = 0;
MainActivity.java:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout=(LinearLayout)findViewById(R.id.myLayout);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mainLayout.setBackgroundResource(R.drawable.yellowgradient);
}
});
mHandler = new Handler();
mRunnable = new Runnable(){
#Override
public void run() {
i++;
if(i==1){
mainLayout.setBackgroundResource(R.drawable.image_one);
}else if(i==2){
mainLayout.setBackgroundResource(R.drawable.image_two);
}else if(i==3){
mainLayout.setBackgroundResource(R.drawable.image_three);
i ==0;
}
mHandler.postDelayed(mRunnable , 10000);
}
};
mHandler .post(mRunnable);
}
}
on onStop():
if(mHandler!=null){
mHandler.removeCallbacks(mRunnable);
}
Done
Use a while loop to repeat.
To delay it for 10 seconds try something like this:
//wait 10 seconds
Button.postDelayed(new Runnable() {
#Override
public void run() {
Button.setClickable(true);
}
}, 10000);

Android Image Button

Android app, i wrote to test image button doesn't work. I have created a image button and implement an event listener for that button. What's wrong with this source code?
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
public class ImageButtonTestApp extends Activity {
ImageButton imageButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void eventListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton1);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(ImageButtonTestApp.this, "ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
u have written setOnClickListener in different method but u didnot call that method any where call that method in oncreate.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
eventListenerOnButton();
}
try this one,
Try it
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(ImageButtonTestApp.this, "ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
});

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);
}
}
}

Application force closing with NullPointerException in logcat

No errors in eclipse.. But whenever I start the application it FC's :(
I am trying to make a app which install scripts to init.d whenever I press the button. I think the problem is the brackets cuz they troubled me ALOT! You can see that they are arranged in an unorganised manner.
MainActivity.java
package com.example.kernel.version;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.stericson.RootTools.Command;
import com.stericson.RootTools.RootTools;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RootTools.remount("/system/", "rw");
Command command = new Command(0, "su", "cp /sdcard/scripts/* /system/etc/init.d/")
{
#Override
public void output(int id, String line)
{
}
};
try {
RootTools.getShell(true).add(command).waitForFinish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
});}}
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" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="141dp"
android:text="Install Scripts" />
</RelativeLayout>
I think NullPointerException on Line, button.setOnClickListener(new View.OnClickListener() {
Because You missed setContentView(R.layout.Activity_main); before accessing Button from layout Xml file.. So your Button button is NULL.
Something Like,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// You missed this code line,
setContentView(R.layout.Activity_main);
Button button= (Button) findViewById(R.id.button);
First create Button instance then add listener
Button button;
public void onCreate(Bundle savedInstanceState) {
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
}
}

Categories