I have one spinner, two adapters and two buttons
when first button is clicked the maleAdapter is called
when the other button is clicked the femaleAdapter is called.
So far this works perfect.
Now. my problem is when each adapter is called two different arrays are called, obviously, BUT i want them to do different things.
Spinner spinner;
String[] maleItems = { "item 1", "item 2", "item 3" };
String[] femaleItems = { "item 3", "item 2", "item 1", "item 0" };
Button maleButton;
Button femaleButton;
ArrayAdapter<String> maleAdapter;
ArrayAdapter<String> femaleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayAdapter<String> maleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, maleItems);
final ArrayAdapter<String> femaleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, femaleItems);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(maleAdapter);
spinner.setOnItemSelectedListener(this);
// Buttons
maleButton = (Button) findViewById(R.id.maleButton);
femaleButton = (Button) findViewById(R.id.femaleButton);
maleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
spinner.setAdapter(maleAdapter);
}
});
femaleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
spinner.setAdapter(femaleAdapter);
}
});
}
Here on my onItemSelected i want to change what happens depending on which button is pressed.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = spinner.getSelectedItemPosition();
SpinnerAdapter adap = spinner.getAdapter();
if (adap.equals(maleAdapter)) {
switch (position) {
case 0:
// do something only the maleAdapter does
break;
case 1:
// do something only the maleAdapter does
break;
case 2:
// do something only the maleAdapter does
break;
}
} else if (adap.equals(femaleAdapter)) {
switch (position) {
case 0:
// do something only the femaleAdapter does
break;
case 1:
// do something only the femaleAdapter does
break;
case 2:
// do something only the femaleAdapter does
break;
}
}
}
My onClick method worked perfect but the adapter changing gives me an error and i dont know why.
Error
01-25 04:11:18.873: E/AndroidRuntime(21871): FATAL EXCEPTION: main
01-25 04:11:18.873: E/AndroidRuntime(21871): java.lang.NullPointerException
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.MainActivity.onItemSelected(MainActivity.java:117)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView.access$200(AdapterView.java:42)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Handler.handleCallback(Handler.java:587)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Handler.dispatchMessage(Handler.java:92)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Looper.loop(Looper.java:130)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.app.ActivityThread.main(ActivityThread.java:3691)
01-25 04:11:18.873: E/AndroidRuntime(21871): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 04:11:18.873: E/AndroidRuntime(21871): at java.lang.reflect.Method.invoke(Method.java:507)
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
01-25 04:11:18.873: E/AndroidRuntime(21871): at dalvik.system.NativeStart.main(Native Method)
final ArrayAdapter<String> maleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, maleItems);
it is in the local scope of onCreate remove it and initilaize the global maleAdpter over there
just remove final ArrayAdapter before maleAdapter and femaleAdapter.
I'd recommend keeping two separate OnItemSelectedListeners, one for each adapter. Now, when you swap the adapters, also swap the OnItemSelectedListener. Plain and simple.
Related
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.
This question already has answers here:
Android - Activity Not Found Exception
(13 answers)
Closed 7 years ago.
So I want to move to a new class using an Intent (from ClassicMode class to Person class) in the check() function. I create a new class but when I get to the startActivity(intent) line I get an error but I can't figure out why.
I used Log.d to try and find the problem with no luck. I hope you can help me. I will put stack trace below, thank you.
ClassicMode.java
public class ClassicMode extends Activity implements AnimationListener{//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
MediaPlayer mpHint;
MediaPlayer mpNext;
MediaPlayer mpWrong;
Animation animationfadein;
Animation animationfadeout;
String fn;
Guesses G;
Score s;
Button [] b = new Button[4];
DatabaseHandler db = new DatabaseHandler(this);
List<String>WrongAnswers=new ArrayList<String>();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
hint.setOnClickListener(hintOnClickListener);
mpHint = MediaPlayer.create(this,R.raw.hint_sound);
mpNext = MediaPlayer.create(this, R.raw.next_flag);
mpWrong = MediaPlayer.create(this, R.raw.wrong_answer);
animationfadein = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animationfadeout = AnimationUtils.loadAnimation(this, R.anim.fade_out);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
WrongAnswers.add(valToAdd1);
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
b[i].startAnimation(animationfadein);
}
}//end of OnCreat
public boolean onOptionsItemSelected(MenuItem item){//actionbar activity
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
#SuppressLint("NewApi")
public void resetQuiz()
{
recreate();
}
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpHint.start();
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
else
G.numOfGuesses--;
int invisblecount=0;
for(int i=0;i<b.length;i++){
if(invisblecount<2){
String buttonText = b[i].getText().toString();
if(buttonText.equals(WrongAnswers.get(0))||buttonText.equals(WrongAnswers.get(1)))
{
b[i].startAnimation(animationfadeout);
b[i].setVisibility(View.INVISIBLE);
invisblecount++;
}
}
}
}
};
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
mpNext.start();
s.score+=5;
resetQuiz();
}
else
{
mpWrong.start();
if(Guesses.numOfGuesses==1)
{
Log.d("kkk", "inside if");
G.setNumOfGuesses(3);
//finish();//כאשר מספר הניחושים
Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
Log.d("lll", "Get Extra");
person.putExtra("Score", extra);
Log.d("sss", "new activ");
startActivity(person);
Log.d("dasdas", "inside Activ");
Toast toast = Toast.makeText(getApplicationContext(), "No more guesses :( Lets see what you made so far...", Toast.LENGTH_SHORT);
toast.show();
/*Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
person.putExtra("Score",extra);
startActivity(person);
Log.d("kkk", "inside person");*/
//return;
}
Guesses.numOfGuesses--;
if(s.score>0)
s.score-=5;
scorenum.setText(String.valueOf(s.score));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private void pic_view(String pic2) {
// TODO Auto-generated method stub
//גישה לדגל לפי שמו וייבוא התמונה
Log.d("Result from pic function " , pic2);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
String uri ="#drawable/";
uri += pic2;
int imageResource = getResources().getIdentifier(uri, pic2, getPackageName());//הצוות התמונה
Drawable res= getResources().getDrawable(imageResource);//ציור התמונה
imageView.setImageDrawable(res);
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Animatoin Stoped", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
}
Person.java
public class Person extends Activity{
EditText name;
Button ok;
TextView enter;
String score;
Map<String,String>Names=new HashMap<String,String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
Intent intent = getIntent();
score = intent.getStringExtra(score);
name =(EditText)findViewById(R.id.namep);
ok =(Button)findViewById(R.id.send);
enter =(TextView)findViewById(R.id.entername);
ok.setOnClickListener(SendActionListener);
}
private OnClickListener SendActionListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Names.put(name.getText().toString(),score);
}
};
}
stacktrace:
04-17 17:45:46.030: D/kkk(5537): inside if
04-17 17:45:46.030: D/lll(5537): Get Extra
04-17 17:45:46.030: D/sss(5537): new activ
04-17 17:45:46.030: I/Timeline(5537): Timeline: Activity_launch_request id:com.example.flagsgame time:93135823
04-17 17:45:46.030: D/AndroidRuntime(5537): Shutting down VM
04-17 17:45:46.030: W/dalvikvm(5537): threadid=1: thread exiting with uncaught exception (group=0x4162cdb8)
04-17 17:45:46.050: E/AndroidRuntime(5537): FATAL EXCEPTION: main
04-17 17:45:46.050: E/AndroidRuntime(5537): Process: com.example.flagsgame, PID: 5537
04-17 17:45:46.050: E/AndroidRuntime(5537): java.lang.IllegalStateException: Could not execute method of the activity
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3830)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View.performClick(View.java:4445)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$PerformClick.run(View.java:18446)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.handleCallback(Handler.java:733)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.dispatchMessage(Handler.java:95)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Looper.loop(Looper.java:136)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-17 17:45:46.050: E/AndroidRuntime(5537): at dalvik.system.NativeStart.main(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: java.lang.reflect.InvocationTargetException
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3825)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 11 more
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.flagsgame/com.example.flagsgame.Person}; have you declared this activity in your AndroidManifest.xml?
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3385)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3627)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3595)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.example.flagsgame.ClassicMode.check(ClassicMode.java:188)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 14 more
The most likely problem is that the Activity is not declared in AndroidManifest.xml. Your error says:
have you declared this activity in your AndroidManifest.xml?
You should first do that.
From this answer on how to do it:
You put it inside of your application element, like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Activity1" android:label="#string/app_name"></activity>
<activity android:name=".Activity2"></activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>
Where .Activity2 is your second activity.
Your intent isn't declared in the Manifest file.
I have a TO DO List, and when I check the checkbox in one Activity I want the CheckBox and the text that is next to the Checkbox to go to another Activity. this is my Adapter:
public class MyItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyItemAdapter(Context context, String[] values) {
super(context, R.layout.item_list, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list, parent, false);
CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
textView.setText(values[position]);
return rowView;
}
public static SparseBooleanArray getCheckedItemPositions() {
// TODO Auto-generated method stub
return null;
}
public static void remove(Object pos) {
// TODO Auto-generated method stub
}
public void changeData(String[] items) {
// TODO Auto-generated method stub
}
public static void setAdapter(MyItemAdapter mAdapter) {
// TODO Auto-generated method stub
}
This is my First Activity code:
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
Bundle extras = new Bundle();
extras.putString("status", "Data Recived");
intent.putExtras(extras);
startActivity(intent);
}
});
}
This is my Second Activity code:
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
And Finaly this is my Log cat:
02-18 10:33:24.779: D/AndroidRuntime(1575): Shutting down VM
02-18 10:33:24.779: W/dalvikvm(1575): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 10:33:24.789: E/AndroidRuntime(1575): FATAL EXCEPTION: main
02-18 10:33:24.789: E/AndroidRuntime(1575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Stanton.quicktodolist/com.Stanton.quicktodolist.MainActivity}: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Looper.loop(Looper.java:130)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 10:33:24.789: E/AndroidRuntime(1575): at dalvik.system.NativeStart.main(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): Caused by: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 10:33:24.789: E/AndroidRuntime(1575): ... 11 more
Please Help me
This line of your stacktrace
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
points you to the error. Line 70 in the MainActivity causes a null pointer. It is often helpful to study and understand stacktraces. If you cannot figure it out yourself, show us the onCreate method of the MainActivity.
I believe that you replace the intent extra by the bundle extra just try this code and let me know pelase
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
//Bundle extras = new Bundle();
// extras.putString("status", "Data Recived");
intent.putExtras("status", "Data Recived");
startActivity(intent);
}
});
}
And the int the second activity
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
// Bundle bundle = intent.getExtras();
String status = intent.getStringExtra("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
I want to use bottom tab in my activity,in my old activity itself having some function,without using seperate activity for tab,can i use tab functions in my activity itself,I tried like this.
public class GinfyActivity extends Activity {
/** Called when the activity is first created. */
public GridviewAdapter mAdapter;
private Spinner spinner1;
public String selectprayer;
ArrayList<GridviewAdapter> results = new ArrayList<GridviewAdapter>();
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_ginfy);
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(GinfyActivity.this,Audioprayer.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(GinfyActivity.this,TTSMeditation.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(GinfyActivity.this,TTSList.class)));
mTabHost.setCurrentTab(0);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listginfy, listimage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (selectprayer.equals("www.ginfy.com"))
{
switch(position)
{
case 0:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
else
{
switch(position)
{
case 0:
Intent new2Activity = new Intent(GinfyActivity.this,YourPrayerActivity.class);
startActivity(new2Activity);
break;
case 1:
Intent new3Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity1.class);
startActivity(new3Activity);
break;
case 3:
Intent new4Activity = new Intent(GinfyActivity.this,ExperiencesActivity.class);
startActivity(new4Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void addListenerOnSpinnerItemSelection() {
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinner1.setSelection(position);
//spinnerCapital.setSelection(position);
selectprayer = (String) spinner1.getSelectedItem();
//Toast.makeText(getBaseContext(), selectprayer, Toast.LENGTH_SHORT).show();
//String myStatesCapital = (String) spinnerCapital.getSelectedItem();
//tvCapital.setText("My State is " + myState + ".And its Capital is "
//+ myStatesCapital);
}
public void onNothingSelected(AdapterView<?> parent) {
}});
}
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
}
public void prepareList()
{
listginfy = new ArrayList<String>();
listginfy.add("Prayers");
listginfy.add("Prayer room");
listginfy.add("God gallery");
listginfy.add("Experiences");
listimage = new ArrayList<Integer>();
listimage.add(R.drawable.ginfyprayer);
listimage.add(R.drawable.poojaroom1);
listimage.add(R.drawable.godsgallery);
listimage.add(R.drawable.temp1);
}
}
I declared that tab functions in mylayout also but my activity is not opening,it display my activity has stopped
is showing somelogcat error.
09-12 08:43:45.615: E/AndroidRuntime(2630): FATAL EXCEPTION: main
09-12 08:43:45.615: E/AndroidRuntime(2630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonandroid/com.example.jsonandroid.GinfyActivity}: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Handler.dispatchMessage(Handler.java:99)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Looper.loop(Looper.java:137)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invokeNative(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invoke(Method.java:511)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-12 08:43:45.615: E/AndroidRuntime(2630): at dalvik.system.NativeStart.main(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): Caused by: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.example.jsonandroid.GinfyActivity.onCreate(GinfyActivity.java:44)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Activity.performCreate(Activity.java:5104)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-12 08:43:45.615: E/AndroidRuntime(2630): ... 11 more
replace these two lines
public class GinfyActivity extends Activity
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
with following
public class GinfyActivity extends TabActivity
TabHost mTabHost = getTabHost();
EDIT
change activity which you want to display in following line.
Intent intentAndroid = new Intent().setClass(this, Your_Activity.class);
And if you want only Tab then it's better to use ActionBar as TabHost is deprecated.
Full Example of TabHost
To use ActionBar here is sample code (use Sherlock or appcompat Library for < API 11)
public class MainActivity extends Activity implements TabListener {
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("TAB 1").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 2").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 3").setTabListener(this));
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start First Activity", Toast.LENGTH_SHORT).show();
break;
case 1:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Second Activity", Toast.LENGTH_SHORT).show();
break;
case 2:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Third Activity", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
For your your complete requirement https://github.com/AdilSoomro/Iphone-Tab-in-Android
I'm trying to create a ListView with 2 TextViews and 1 Button. When the users click in the button the activity will finish(); and pass the result to another view. I followed this tutorial . But for some reason when i click to start that activity my application crashes! Here is the 3 files from my app that are relevant.
List Structure Data:
public class formulasListData {
private String formulasName;
private String formulasDefinition;
public formulasListData(String formulasName, String formulasDefinition) {
super();
this.formulasName = formulasName;
this.formulasDefinition = formulasDefinition;
}
public String getFormulasName() {
return formulasName;
}
public void setFormulasName(String formulasName) {
this.formulasName = formulasName;
}
public String getFormulasDefinition() {
return formulasDefinition;
}
public void setFormulasDefinition(String formulasDefinition) {
this.formulasDefinition = formulasDefinition;
}
}
The List Adapter:
public class formulasListAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<formulasListData> formulasList;
public formulasListAdapter(Context context, List<formulasListData> formulasList) {
this.context = context;
this.formulasList = formulasList;
}
#Override
public int getCount() {
return formulasList.size();
}
#Override
public Object getItem(int position) {
return formulasList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View rowView, ViewGroup parent) {
formulasListData entry = formulasList.get(position);
if(rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.formulas_row, null);
}
TextView formulasName = (TextView) rowView.findViewById(R.id.formulas_name);
formulasName.setText(entry.getFormulasName());
TextView formulasDefinition = (TextView) rowView.findViewById(R.id.formulas_definition);
formulasDefinition.setText(entry.getFormulasDefinition());
Button btnSelect = (Button) rowView.findViewById(R.id.selectFormula);
btnSelect.setFocusableInTouchMode(false);
btnSelect.setFocusable(false);
btnSelect.setOnClickListener(this);
btnSelect.setTag(entry);
return rowView;
}
#Override
public void onClick(View view) {
formulasListData entry = (formulasListData) view.getTag();
}
}
And the activity that should display the list.
public class FormulasList extends Activity {
private static final int FORMULA_0 = 0;
private static final int FORMULA_1 = 1;
private static final int FORMULA_2 = 2;
private static final int FORMULA_3 = 3;
private static final int FORMULA_4 = 4;
private static final int FORMULA_5 = 5;
private static final int FORMULA_6 = 6;
// private static final int FORMULA_7 = 7;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
ListView formulasListView = (ListView) findViewById(R.id.formulas_list);
formulasListView.setClickable(true);
final List<formulasListData> formulasList = new ArrayList<formulasListData>();
final String[] formulasName = new String[] {"Circunference of a Circle:",
"Area of a Circle:",
"Volume of a Sphere:",
"Area Triangle:",
"Area Square:",
"Volume of a Cube:",
"Pithagorean Theorem:"};
final String[] formulasDefinition = new String[] {"2 × π × r",
"π × r²",
"(4/3) × π × r³",
"(b × h)/2",
"side²",
"side³",
"a² + b² = c²"};
// formulasList.add(new formulasListData(formulasName, formulasDefinition));
formulasList.add(new formulasListData(formulasName[0], formulasDefinition[0]));
formulasList.add(new formulasListData(formulasName[1], formulasDefinition[1]));
formulasList.add(new formulasListData(formulasName[2], formulasDefinition[2]));
formulasList.add(new formulasListData(formulasName[3], formulasDefinition[3]));
formulasList.add(new formulasListData(formulasName[4], formulasDefinition[4]));
formulasList.add(new formulasListData(formulasName[5], formulasDefinition[5]));
formulasList.add(new formulasListData(formulasName[6], formulasDefinition[6]));
SharedPreferences settings = getSharedPreferences(SettingsActivity.PREF_NAME, MODE_PRIVATE);
SettingsActivity.newTheme = settings.getInt("themeCustom", 0);
if(SettingsActivity.newTheme == SettingsActivity.THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_formulas);
formulasListAdapter adapter = new formulasListAdapter(this, formulasList);
formulasListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long index) {
Intent intent= getIntent();
Bundle b = new Bundle();
switch (position) {
case FORMULA_0:
b.putString("key0", formulasDefinition[0]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_1:
b.putString("key0", formulasDefinition[1]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_2:
b.putString("key0", formulasDefinition[2]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_3:
b.putString("key0", formulasDefinition[3]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_4:
b.putString("key0", formulasDefinition[4]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_5:
b.putString("key0", formulasDefinition[5]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_6:
b.putString("key0", formulasDefinition[6]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
}
});
formulasListView.setAdapter(adapter);
}
}
Thank you very much!!
EDIT: Here is the LogCat
05-01 20:06:54.436: D/libEGL(4820): loaded /system/lib/egl/libEGL_tegra.so
05-01 20:06:54.456: D/libEGL(4820): loaded /system/lib/egl/libGLESv1_CM_tegra.so
05-01 20:06:54.466: D/libEGL(4820): loaded /system/lib/egl/libGLESv2_tegra.so
05-01 20:06:54.486: D/OpenGLRenderer(4820): Enabling debug mode 0
05-01 20:06:54.536: D/dalvikvm(4820): GC_CONCURRENT freed 170K, 4% free 7509K/7808K, paused 4ms+10ms, total 38ms
05-01 20:06:59.976: D/AndroidRuntime(4820): Shutting down VM
05-01 20:06:59.976: W/dalvikvm(4820): threadid=1: thread exiting with uncaught exception (group=0x40cde930)
05-01 20:06:59.976: E/AndroidRuntime(4820): FATAL EXCEPTION: main
05-01 20:06:59.976: E/AndroidRuntime(4820): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabilheri.marcuscalculatorv2/com.gabilheri.marcuscalculatorv2.FormulasList}: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Looper.loop(Looper.java:137)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 20:06:59.976: E/AndroidRuntime(4820): at dalvik.system.NativeStart.main(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): Caused by: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.gabilheri.marcuscalculatorv2.FormulasList.onCreate(FormulasList.java:30)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Activity.performCreate(Activity.java:5104)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-01 20:06:59.976: E/AndroidRuntime(4820): ... 11 more
Try moving
setContentView(R.layout.activity_formulas);
To the start of the method. Right after the super call.
You are trying to use gui controls before initializing the activity layout