I have slider app,on sliding using left button there will be a listview, on clicking list view there should open second activity.i used Intent for that but my android app automatically close after clicking in listview.
MainActivity.java
package com.example.slide_menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.navdrawer.SimpleSideDrawer;
public class MainActivity extends Activity {
SimpleSideDrawer slide_me;
Button left_button, right_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slide_me = new SimpleSideDrawer(this);
slide_me.setLeftBehindContentView(R.layout.left_menu);
slide_me.setRightBehindContentView(R.layout.right_menu);
left_button = (Button) findViewById(R.id.left_buton);
right_button = (Button) findViewById(R.id.right_buton);
left_button.setOnClickListener(new View.OnClickListener() {
private ListView l1;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
slide_me.toggleLeftDrawer();
l1=(ListView)findViewById(R.id.listView1);
l1.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.dataelements)));
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
switch(position){
case 0: Intent newActivity0 = new Intent(MainActivity.this,Lone.class);
startActivity(newActivity0);
break;
// case 1: Intent newActivity1 = new Intent(MainActivity.this,Maruti.class);
// startActivity(newActivity1);
// break;
// case 2: Intent newActivity = new Intent(this, olympiakos.class);
// startActivity(newActivity);
// break;
// case 3: Intent newActivity = new Intent(this, karaiskaki.class);
// startActivity(newActivity);
// break;
// case 4: Intent newActivity = new Intent(this, reservetickets.class);
// startActivity(newActivity);
// break;
}
}
});
}
});
right_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
slide_me.toggleRightDrawer();
}
});
}
}
left_menu
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Left Menu"
android:textColor="#000000" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
String.xml
<resources>
<string name="app_name">slide_menu</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">Slide Demo</string>
<string-array name="dataelements">
<item>one</item>
<item>two</item>
<item>three</item>
<item>four</item>
<item>five</item>
</string-array>
</resources>
Lone.java(mysecondactivityfile)
package com.example.slide_menu;
import android.app.Activity;
import android.os.Bundle;
public class Lone extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lo);
}
}
Lo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lone scond"
android:textAppearance="?android:attr/textAppearanceLarge" />
Related
How can i exit my app on navbar menu item click . I have used navbar for other tasks but i am slightly confused about exiting the app directly on item click
switch (menuItem.getItemId()) {
case R.id.nav_home:
break;
case R.id.nav_delete:
TODOViewModel.deleteAllTasks();
Toast.makeText(this, "All TODOs Deleted", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_logout:
Intent intent = new Intent(MainActivity.this, ActivityLogin.class);
startActivity(intent);
finish();
break;
case R.id.nav_exit:
default:
}
Use finish() or System.exit(0).
This is the XML File used
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/txt1" android:text="txt1" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/txt2" android:text="txt2"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/btn1"
android:text="Close App" />
</LinearLayout>
The Java file
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class testprj extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
}
}
i need to change my text in the header when i click on the textview , i made my best effort to do somethings, but i m not getting the result
i will post the code and if anyone can help me out and tell me where i m going wrong , it will be of great help
this is my results.xml where my listview and the header with textview(the one which is to be set inside the java code) is there ,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White" >
<RelativeLayout
android:id="#+id/rltHeader"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#27acc3" >
<ImageView
android:id="#+id/imgBackReuslt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:onClick="onClick"
android:src="#drawable/arrow" />
<TextView
android:id="#+id/txtHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/White"
android:textSize="20dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/rltHeader"
android:layout_marginRight="5dp"
android:divider="#color/LightGray"
android:dividerHeight="4px" >
</ListView>
</RelativeLayout>
this is my another xml where i have displayed how the listviews every Row will appear
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<RelativeLayout
android:id="#+id/rltRow"
android:layout_width="17dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:background="#drawable/r_list" >
</RelativeLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="83dp"
android:layout_height="80dp"
android:layout_alignBottom="#+id/rltRow"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:layout_toRightOf="#+id/rltRow"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="14dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignLeft="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/rltRow"
android:layout_alignLeft="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignTop="#+id/imageView1"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="12dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="12dp" />
</RelativeLayout>
</RelativeLayout>
Now the Java part
This is the List_Activity class where i have displayed all the textviews , there are 6 textviews which when clicked , an activity will appear Results.java , for all the textviews when clicked the same activity Results.java is opened.
package com.demo.Test;
import android.app.ActionBar;
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;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class List_Activity extends Activity {
ImageView iv;
TextView t1, t2, t3, t4, t5, t6;
String header_result = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_info);
iv = (ImageView)findViewById(R.id.imgBackReuslt);
t1 = (TextView) findViewById(R.id.text1);
t2 = (TextView) findViewById(R.id.text2);
t3 = (TextView) findViewById(R.id.text3);
t4 = (TextView) findViewById(R.id.text4);
t5 = (TextView) findViewById(R.id.text5);
t6 = (TextView) findViewById(R.id.text6);
t1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String str = headervalue.getText().toString();
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Self", header_result);
startActivity(intent);
}
});
t2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Mary(Wife)", header_result);
startActivity(intent);
}
});
t3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// name = t3.getText().toString();
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Alex(Child-1)", header_result);
startActivity(intent);
}
});
t4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Steven(Child-2)", header_result);
startActivity(intent);
}
});
t5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Robert(Father)", header_result);
startActivity(intent);
}
});
t6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Diana(Mother)", header_result);
startActivity(intent);
}
});
}
public void onClick(View v) {
super.onBackPressed();
finish();
}
}
Now the main class Results.java , the activity which opens when clicked on the textviews described the previous class
package com.demo.Test;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Results extends Activity{
TextView header;
ImageView iv;
ListView lv;
String title;
int[] images = { R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.photo_bg, R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.b_list, R.drawable.g_list, R.drawable.r_list,
R.drawable.v_list };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
iv = (ImageView) findViewById(R.id.imgBackReuslt);
header = (TextView) findViewById(R.id.txtHeader);
lv = (ListView) findViewById(R.id.listView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
title = extras.getString("header_result");
}
ResultsAdapter adapter = new ResultsAdapter(getBaseContext(), doc,
diag, dt, images, docname, diagname);
lv.setAdapter(adapter);
}
so what changes i have to make so that the header text gets changed when i click on the textviews in the List_Activity accordingly
any suggestions are welcomed
Do you mean changing the title of your action bar in each activity?
you can do it by calling this short code
getActionBar().setTitle("the title you want");
you can check this link http://developer.android.com/guide/topics/ui/actionbar.html
Hope it helps, and tell me if you need anything else ;)
according to what you want
t2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
// this header_result you want pass it textview (txtHeader)
// prefer don't write long description in key of your extra
intent.putExtra("Results for Mary(Wife)", header_result);
startActivity(intent);
}
});
put in your jave file that contain
header = (TextView) findViewById(R.id.txtHeader);
header.setText("YourPassingValue"); // in your case getIntent().getStringExtra("Results for Mary(Wife)");
Refine your code
if you want move from activity yo anther
Intent intent = new Intent (YourFirstActivity.this , SecondActivity.class);
intent.putExtra("Result", PassingVariable); // prefer to make the key of your extra short to make east to call back , PassingVariable is what ever you want pass to the anther activity
startActivity(intent);
in Anther activity get you extra data
in your on create method
String PassedData = getIntent().getStringExtra("Result"); // Result is Your used key
make any thing with passed data
in Your case you want set it on Textview
t2.setText(PassedData);
i have an android application that display a flag and group of radio buttons that each time the user check any radio button the application will display a button that allow to go to the next page using intent .
what i need is that each time the user check the right answer the system must calculate its score until the application finish .
the score will start by 0/0 and will finish after four rounds.
for now i need just to display the score of the user in the second page
i will appreciate any help
MainActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnS;
RadioGroup rdgS;
RadioButton rdS1, rdS2, rdS3, rdS4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgS = (RadioGroup) findViewById(R.id.rdg1);
rdgS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(rdS1.isChecked()||rdS2.isChecked()||rdS3.isChecked()||rdS4.isChecked()){
btnS.setVisibility(View.VISIBLE);
}
}
});
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (v.getId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.hint_icon:
ShowAlertDialog();
break;
case R.id.about_icon:
Toast.makeText(this, "developed by Georges Matta",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void ShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hint")
.setMessage("The famouse sport is Bullfighting")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
edited code
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
result = String.valueOf(dbl);
i.putExtra("score", result);
break;
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="34dp"
android:src="#drawable/spanish" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Gess the Country of the flag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#CCFF99" />
<RadioGroup
android:id="#+id/rdg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView1" >
<RadioButton
android:id="#+id/rd_s1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Egypt"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="China"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spanish"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/radioGroup1"
android:layout_below="#+id/radioGroup1"
android:text="Italy"
android:textColor="#CCFF99" />
</RadioGroup>
<Button
android:id="#+id/btn_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/rdg1"
android:layout_below="#+id/rdg1"
android:text="Next"
android:visibility="invisible" />
</RelativeLayout>
SecondActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class SecondActivity extends Activity {
TextView txt_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
txt_result = (TextView) findViewById(R.id.txtResult);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("score");
txt_result.setText(value);
}
}
#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;
}
}
activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<TextView
android:id="#+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Simple solution is to modify your switch case as follows:
...
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
...
...
After this since your are passing in int values, you should use getInt() method. In your oncreate of SecondActivity do this:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = String.valueOf(extras.getInt("score"));
txt_result.setText(value);
}
There is a problem here:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("showResult", result);
startActivity(intent);
This should match extras.getString("score"); string in the second activity, so change it to:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("score", result);
startActivity(intent);
In your onClick(View v) handler, v refers to the button btn_s, therefore switch (v.getId()) will not work since v.getId() will always return id of the button, i.e. R.id.btn_s.
You need to query states of the radio button separately, for example use
if (rdS1.isChecked()) {
// first ratio button is checked
} else if (rdS2.isChecked()) {
// second is checked
} else if ...
Replace your switch (v.getId()) in onClick(View v) with that if.
I am trying to set reminders. There is a spinner with 5 values (1,2,3,4,5). Let's say if user selects 3 from the spinner there should be 3 "Add Time" buttons displayed. Similarly if user selects 5, five "Add Time" button should be displayed.
User presses "Add Time" button and time picker will be displayed to select time for the reminders. I've created spinner through xml from res/string folder and set an array of 5 item (1,2,3,4,5). I don't know to display these "Add Time" buttons as per the selection of value from the spinner.
Would greatly appreciate any suggestions/guidance.
Thanks a lot...
package com.example.medicationreminder;
import jim.h.common.android.lib.zxing.config.ZXingLibConfig;
import jim.h.common.android.lib.zxing.integrator.IntentIntegrator;
import jim.h.common.android.lib.zxing.integrator.IntentResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
import com.example.medicationreminder.InteractiveArrayAdapter.ViewHolder;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class MedInfo extends Activity implements OnClickListener{
private Button daily, weekly, mScanBarcode;
private Handler handler = new Handler();
private ZXingLibConfig zxingLibConfig;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_med_info);
mScanBarcode = (Button) findViewById(R.id.Barcodescanner);
mScanBarcode.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.med_info, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == mScanBarcode)//When scan barcode button is clicked
{
IntentIntegrator.initiateScan(MedInfo.this, zxingLibConfig);//Intent that opens camera for scanning through zxing Library
}
/* else if(v == weekly)
{
Intent weekly = new Intent(MedInfo.this,Weekly.class);
startActivity(weekly);
} */
else if(v == daily)
{
Intent daily = new Intent(MedInfo.this, DailyMed.class);
startActivity(daily);
}
}
//The method that cathes the result after scanning is done
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case IntentIntegrator.REQUEST_CODE:
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
resultCode, data);
if (scanResult == null)
{
return;
}
final String result = scanResult.getContents();//scanned result
if (result != null)
{
handler.post(new Runnable()
{
#Override
public void run()
{
showScannedResult(result);//opening pop up showing scanned result
}
});
}
break;
default:
}
}
//Pop up dialog showing scanned result
private void showScannedResult(String result)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scanned Result")
.setMessage(result)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
//Array list for selection of Days
public class Weekly extends ListActivity {
public void onCreate1(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
list.add(get("Monday"));
list.add(get("Tuesday"));
list.add(get("Wednesday"));
list.add(get("Thursday"));
list.add(get("Friday"));
list.add(get("Saturday"));
list.add(get("Sunday"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private Model get(String s) {
return new Model(s);
}
// Spinner item selection and add button
public class spinning extends Activity implements AdapterView.OnItemSelectedListener{
LinearLayout list;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceSate) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceSate);
setContentView(R.layout.activity_med_info);
spinner = (Spinner)findViewById(R.id.spinner1);
list = (LinearLayout)findViewById(R.id.list);
ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter.createFromResource(this,
R.array.dose_arrays, android.R.layout.simple_spinner_item);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterSpinner);
spinner.setOnItemSelectedListener(this);
}
public void addButton(int number){
list.removeAllViews();
for(int i = 0; i<number;i++){
Button button = new Button(getApplicationContext());
button.setText("Add Time");
list.addView(button);
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {
// TODO Auto-generated method stub
switch(i){
case 0:
addButton(1);
break;
case 1:
addButton(2);
break;
case 2:
addButton(3);
break;
case 3:
addButton(4);
break;
case 4:
addButton(5);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
}
Medinfo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/android"
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=".MedInfo" >
<EditText
android:id="#+id/MedName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_alignTop="#+id/radioGroup1"
android:ems="10"
android:hint="Name of Medicine" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Barcodescanner"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/MedName"
android:layout_below="#+id/MedName"
android:layout_marginTop="14dp"
android:text="Scan Barcode" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Barcodescanner"
android:layout_below="#+id/Barcodescanner"
android:layout_marginTop="44dp"
android:text="Dose per day"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:entries="#array/dose_arrays"
android:prompt="#string/dose_prompt" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner" android:id="#+id/list">
</LinearLayout>
<CheckBox
android:id="#+id/checkMon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="114dp"
android:text="Mon" />
<CheckBox
android:id="#+id/checkTue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkMon"
android:layout_alignBottom="#+id/checkMon"
android:layout_toRightOf="#+id/AddTime"
android:text="Tue" />
<CheckBox
android:id="#+id/checkWed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkTue"
android:layout_alignBottom="#+id/checkTue"
android:layout_centerHorizontal="true"
android:text="Wed" />
<CheckBox
android:id="#+id/checkThur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/checkWed"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/checkWed"
android:text="Thur" />
<CheckBox
android:id="#+id/checkFri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/checkTue"
android:layout_marginTop="27dp"
android:layout_toRightOf="#+id/radioGroup1"
android:text="Fri" />
<CheckBox
android:id="#+id/checkSat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkFri"
android:layout_alignBottom="#+id/checkFri"
android:layout_alignLeft="#+id/checkTue"
android:text="Sat" />
<CheckBox
android:id="#+id/checkSun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkSat"
android:layout_alignBottom="#+id/checkSat"
android:layout_alignLeft="#+id/checkWed"
android:text="Sun" />
<!--
<Button
android:id="#+id/AddTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView1"
android:layout_marginTop="49dp"
android:text="Add Time" />
-->
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Medication Reminder</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title_activity_med_info">MedInfo</string>
<string name="dose_prompt">Choose a Dose</string>
<string-array name="dose_arrays">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
<string name="check_Monday">Monday</string>
<string name="check_Tuesday">Tuesday</string>
<string name="check_Wednesday">Wednesday</string>
<string name="check_Thursday">Thursday</string>
<string name="check_Friday">Friday</string>
<string name="check_Saturday">Saturday</string>
<string name="check_Sunday">Sunday</string>
<string name="title_activity_daily_med">DailyMed</string>
<string name="title_activity_weekly">Weekly</string>
<string name="title_activity_daily__addtime">Daily_Addtime</string>
<string name="title_activity_interactive_adapter">InteractiveAdapter</string>
<string name="title_activity_interactive_array_adapter">InteractiveArrayAdapter</string>
<string name="title_activity_barcode_scanner">Barcode_scanner</string>
</resources>
try this code.
ActivityMain.class
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener{
LinearLayout list;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ativity_main);
spinner = (Spinner) findViewById(R.id.spinner);
list = (LinearLayout)findViewById(R.id.list);
ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter.createFromResource(this,
R.array.number, android.R.layout.simple_spinner_item);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterSpinner);
spinner.setOnItemSelectedListener(this);
}
public void addButton(int number){
list.removeAllViews();
for(int i = 0; i<number; i++){
Button button = new Button(getApplicationContext());
button.setText("Add Time");
list.addView(button);
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
addButton(1);
break;
case 1:
addButton(2);
break;
case 2:
addButton(3);
break;
case 3:
addButton(4);
break;
case 4:
addButton(5);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_centerHorizontal="true" android:layout_alignParentTop="true"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner" android:id="#+id/list">
</LinearLayout>
strings.xml
<string-array name="number">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
Hope, it will be helpful :)
In my app there is two layout first.xml and activity_main.xml. In first Layout there is a button and ListView (Code):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/listView_items"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
And this Layout is connected with MainActivty:
package com.example.listview2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView lvItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivity(intent);
}
});
}
}
And then there is second layout activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ListActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/input">
<EditText
android:id="#+id/editText_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#+id/input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
And this activity is connected to ListActivity:
package com.example.listview2;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ListActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
The idea of app is very simple. When you start the app, it start MainActivity which is button with ListView. Then you press button to open ListActivity to create new ListView item and this is my question: how can I add to ListView an item from another Activity?
I think you got the logic a little bit messed up there. For example, you are referencing in ListActivity a view that does not exist in its layout:
lvItem = (ListView)this.findViewById(R.id.listView_items);
listView_items is defined in first.xml layout, which means that the lvItem reference in ListActivity will be null.
In any case, here is a better way to design your app:
1- Have your MainActivity act as the central component of the app. Since it is displaying the listView, it should also be responsible of adding/removing items from it. MainActivity would then start ListActivity when a user wants to add a new item to the list.
2- Have your ListActivity act as a simple interface to get the user's information, and retuning it to your MainActivity.
In this case, the solution is to use startActivityForResult(). Here is a small rewrite to make it work:
public class MainActivity extends Activity {
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivityForResult(intent, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
itemArrey.add(0,result);
itemAdapter.notifyDataSetChanged();
}
else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
Now, for ListActivity, you will keep the same code, but add the following in your btnAdd onClickListener:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",etInput);
setResult(RESULT_OK,returnIntent);
finish();
You obviously will want to add input verification and other niceties.
First of all you cannot be doing
lvItem = (ListView)this.findViewById(R.id.listView_items);
you will get Null Pointer exception when lvItem is used as listView_items does not exist in your activity_main layout.
The right way to make your design work is to send "itemArrey" back as bundle extra in the intent you create for setResult.