I want to implement 2 activities , one is a listview with image and text which works well now. The other one is a onClicklistener when I click any ListItem it will start another activity to show more information, with 1 previous button and next button to see the Prev information or next. However there is something wrong with the button. It can only see the previous one and next one once. Which means you can't click the next button twice. Any suggestions will be appreciated .
Here is my main activity code
package com.example.manchesterunited;
import com.example.manchesterunited.R;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
static PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter adapter = new CustomAdapter(this);
setListAdapter(adapter);
}
public void onListItemClick(ListView l,View v, int pos, long id){
int playerId = (int)id;
Toast.makeText(getApplicationContext(),"Selected "+data.getName(pos),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, InfoActivity.class);
intent.putExtra("playerId", playerId);
startActivity(intent);
}
}
And here is the second activity
package com.example.manchesterunited;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InfoActivity extends Activity {
TextView dobText;
TextView pobText;
TextView internationalText;
Button prevButton;
Button nextButton;
PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
dobText = (TextView)findViewById(R.id.textView1);
pobText = (TextView)findViewById(R.id.textView2);
internationalText = (TextView)findViewById(R.id.textView3);
prevButton = (Button)findViewById(R.id.prev);
nextButton = (Button)findViewById(R.id.next);
Intent intent = getIntent();
final int playerId = intent.getExtras().getInt("playerId");
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId-1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_info, menu);
return true;
}
}
You're not updating the playerID.
You're just getting a new ID.
you should put
int newId = playerId+1;
playerID = newId; //insert this line
so that when you click again,
playerID gets updated.
You are always adding just 1 to player ID which will now point to next item. But as soon as you re-click the button it will have the same player ID that was passed through intent. So again it will add in the same value. Make a new variable which will store the current player ID that is visible and keep on incrementing it then you will be able to browse next and vice versa in the previous case.
You can't increment player ID as it has been declared as final, so you can either make a global variable or put a variable in intent and increment it on button clicks.
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//make newId global then it will work. And keep on updating it when the button is clicked accordingly.
newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
Try this on InfoActivity,
private int playerId;
...
...onCreate(...){
...
playerId = intent.getExtras().getInt("playerId");
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId--;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId++;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
}
Related
My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.
I wish to have questions that change to the next question in the sequence onClick but I'm having trouble creating the array of questions and writing the onClick code for that portion.
*Too add more context to the app it will be a questionaire app with a question above an editText field and the users inputs will show up in its respective box at the top of the screen.
package com.example.greg;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class menu extends Activity {
Button mButton;
EditText mEdit;
int questionNumber = 0;
String [] questions;
int numberOfQuestions = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.userAnswereditText);
questions=new String[numberOfQuestions];
questions[0]="This is first question?";
questions[1]="This is second question?";
final TextView [] myTexts = new TextView[2];
myTexts[0]=(TextView)findViewById(R.id.varATextView);
myTexts[1]=(TextView)findViewById(R.id.varBTextView);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
myTexts[questionNumber].setText(mEdit.getText().toString());
mEdit.setText(null);
questionNumber++;
if(questionNumber < numberOfQuestions)
questionTextViewHolder.setText(questions[questionNumber]);
else
Toast.makeText(menu.this,"No more questions!",Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
I have 3 classes. In every class I have 2 buttons like yes and no.
I want to pass 1 for yes and 0 for no.Finally I want to count the total number,
I mean if someone presses ' yes ' every time then it should be 3.
How to do it?`
passing values by buttons and count the whole thing
//this is 1st class
package com.atlantis.learnactivities;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Main.this,Second.class));
}
});
Button b2 = (Button) findViewById(R.id.b2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Main.this,Second.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//this is 2nd class
package com.atlantis.learnactivities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Second extends Activity {
String gender =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button b3 = (Button) findViewById(R.id.b3);
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Second.this,Three.class));
}
});
Button b4 = (Button) findViewById(R.id.b4);
b4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Second.this,Four.class));
}
});
}
}
Use sharedPreference.
When click button add an integer value.
To add
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("btn_value", "value");
editor.commit();
To retrieve data from shared preference
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int value = prefs.getInt("btn_value", -1);
In your current Activity, create a new Intent:
Intent i = new Intent(Main.this, Second.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the Second Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
You don't need to use SharedPreferences to pass data in the same application.
If you don't need to Store the values and just pass it from one class to the next, use putExtra with intent.
Eg. Inside your click listener:
intent.putExtra("value", 1);
//or intent.putExtra("value", "1") , depending on whether you want to use it as a String or int
And in the class you are passing the value to, retrieve it
this.getIntent().getExtras().getString("value");
//this.getIntent().getExtras().getInt("value");
check:
http://pkhandroid.wordpress.com/2012/10/02/post9-intent-message-passing-within-activities/
http://mobileorchard.com/android-app-development-using-intents-to-pass-data-and-return-results-between-activities/
I want to alert dialog to display if the password and login id doesn't match. I tried the following code, but when i run if the text are same then it executes, but in the case if the password and Login Id doesn't match an alert is supposed to be display but instead the process exits saying unfortunately your project is ended.
I have attached my code below
package com.example.explicitintent;
import java.security.PublicKey;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1, b2,b3;
EditText e1, e2;
String username="saras", password="greek";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText0001);
e2 = (EditText) findViewById(R.id.editText0002);
b1 = (Button) findViewById(R.id.button0002);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (username.equals(e1.getText().toString()) && (password.equals(e2.getText().toString())))
{
Intent b = new Intent(MainActivity.this,Contacts.class);
String s = e1.getText().toString();
String s1 = e2.getText().toString();
b.putExtra("d1", s);
b.putExtra("d2", s1);
startActivity(b);
}
else
{
AlertDialog.Builder alt = new AlertDialog.Builder(getApplicationContext());
alt.setIcon(R.drawable.ic_launcher);
alt.setTitle("WARNING");
alt.setMessage("Do u want to re-enter password");
alt.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
}
});
alt.setNegativeButton("NO",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
Toast.makeText(getApplicationContext(),"OK", Toast.LENGTH_SHORT).show();
}
});
alt.show();
}
}
});
b2 = (Button) findViewById(R.id.button0003);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent c = new Intent(MainActivity.this, Reset.class);
startActivity(c);
}
});
b3 = (Button) findViewById(R.id.button1);
b3.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(),"Password Saved", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Change this line
AlertDialog.Builder alt = new AlertDialog.Builder(getApplicationContext());
to
AlertDialog.Builder alt = new AlertDialog.Builder(arg0.getContext());
and you should change arg0 to something meaningful like view or v. If that doesn't work then please post the logcat so we can see what error you are getting. You need to use the appropriate Context for the situation and here you want the AlertDialog to use the Activity Context which is the same Context that your Button (or arg0) uses.
Note MainActivity.this will do the same thing here as argo.getContext() but I was recently informed that it is bad practice for reasons such as if you want to re-use this code then you have to change the activity name part of the code. Its a less dynamic way of accessing the Context.
Here is a good SO answer that addresses the issue of Context. It can be a tricky concept to grasp at first so you may want to read over it a few times and keep it close by.
Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}