I am developing an app which has a home screen consisting of list view(Home Activity).User clicks on list item and new activity is started named as Topic.This activity also consist of list view. Home is set as parent activity for Topic.
Now in Topic class i am again calling Topic class using intent.
So a user clicks on a list item in Home activity,which opens a new Topic activity.User again clicks on list item ,and another new activity Topic is created,so we are at rd level. My app is working fine till here, but as Parent for Topic is Home,so as soon as i press back or up button,irrespective of where i am in my app,it is always the Home class which opens.
How to handle this so that all user can traverse back to each activity.
The code is given below:
Home.java
package com.example.guninder.home;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
import static android.widget.AdapterView.*;
public class Home extends AppCompatActivity implements FetchDataListener {
private ProgressDialog dialog;
private ListView HomeListview;
private DrawerLayout home_drawer_layout;
private ListView Menu_option_list;
private String[] Menu_list;
private ActionBarDrawerToggle drawerToggle;
private ApplicationAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
HomeListview = (ListView) findViewById(R.id.listView1);
itemClickListener(HomeListview);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Menu_list = getResources().getStringArray(R.array.Menu_options);
home_drawer_layout = (DrawerLayout) findViewById(R.id.home_drawable);
Menu_option_list = (ListView) findViewById(R.id.home_menu_option);
Menu_option_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, Menu_list));
// home_Toolbar.setNavigationIcon(R.drawable.ic_drawer);
drawerToggle = new ActionBarDrawerToggle(this, home_drawer_layout, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawerToggle.setDrawerIndicatorEnabled(true);
home_drawer_layout.setDrawerListener(drawerToggle);
initView();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/connect.php";
String url = "http://192.168.0.25/connect.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,null);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// create new adapter
adapter = new ApplicationAdaptor(this, data);
HomeListview.setAdapter(adapter);
// set the adapter to list
//setListAdapter(adapter);
}
public void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(drawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void itemClickListener(final ListView HomeListview) {
HomeListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = adapter.getItem(position);
Intent intent = new Intent(Home.this, Topic.class);
intent.putExtra("topic_name",app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
Toast toast=Toast.makeText(Home.this,app.getParentContent(),Toast.LENGTH_LONG);
startActivity(intent);
}
});
}
}
Topic.java
package com.example.guninder.home;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class Topic extends AppCompatActivity implements FetchDataListener {
String topicName, ParentContent;
int topic_id;
//TextView txv;
ProgressDialog Topicdialog;
ListView topiclistView;
ApplicationAdaptor tAdaptor;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic);
Bundle extras = getIntent().getExtras();
if (extras == null) {
topicName = null;
}
topicName = extras.getString("topic_name");
topic_id = extras.getInt("topic_id");
ParentContent = extras.getString("Content");
txv = (TextView) findViewById(R.id.content);
txv.setMovementMethod(ScrollingMovementMethod.getInstance());
if (ParentContent.isEmpty()) {
txv.setVisibility(txv.GONE);
} else {
txv.setText(ParentContent);
}
setTitle(topicName);
topiclistView = (ListView) findViewById(R.id.topiclistView1);
itemClickListener(topiclistView);
topicinitView();
}
#Override
public void onPause(){
super.onPause();
}
public void onResume(){
super.onResume();
}
private void topicinitView() {
// show progress dialog
Topicdialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/Topic.php";
String url = "http://192.168.0.25/Topic.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url, String.valueOf(topic_id));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_topic, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFetchComplete(List<Application> data) {
if (Topicdialog != null) Topicdialog.dismiss();
// create new adapter
tAdaptor = new ApplicationAdaptor(this, data);
topiclistView.setAdapter(tAdaptor);
// set the adapter to list
//setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (Topicdialog != null) Topicdialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void itemClickListener(final ListView TopicListview) {
TopicListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = tAdaptor.getItem(position);
if (app.getChildExist()) {
Intent intent = new Intent(Topic.this, Topic.class);
intent.putExtra("topic_name", app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
// Toast toast = Toast.makeText(Topic.this, app.getTopic_id(), Toast.LENGTH_LONG);
//toast.show();
startActivity(intent);
finish();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guninder.home" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Home"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Topic"
android:label="#string/title_activity_topic"
android:parentActivityName=".Home" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.guninder.home.Home" />
</activity>
<activity
android:name=".SetNotification"
android:label="#string/title_activity_set_notification"
android:theme="#android:style/Theme.Dialog" >
</activity>
</application>
</manifest>
Please help.Thanks in advance
Comment finish() inside the listitem click in topic class. it will solve your problem.
What you could do is, do not set Home as the parent of Topic.
This way when user presses back, the previous activity that was open will be shown to the user.
Related
I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn't work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here's my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MenuActivity"
android:label="#string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here's the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
#Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can't show you my Logcat because it doesn't work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
...Please HELP ME !
To open a new activity you simply have to call it like this inside the onClick method.
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
So your onClick method will look like this.
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
}
Hope this helps.
Is because you say MainActivity.this, but you aren't in the MainActivity context.
You could make a reference of your current context in onCreate() and save it in a field:
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
//rest of your code here
}
and use it as:
Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);
Go to your manifest file, you will for your MainActivity manifest:
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
Just copy them and paste them for your MenuActivity.
I had the same same problem than you and it worked for me, but I don't know why.
Good luck!
first make sure your AndroidManifest.xml file contain declaration of all Activities in your app, like
<activity android:name=".MenuActivity"/>
then you create new intent and start it where you need to start the second Activity
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
I have a MainActivity that has a NavigationDrawer in it.In the menu of the drawer each item starts a new activity.Now when i press the Back button from any of these activities i end up in a blank page,when i press it again it goes to main activity.What i want is to go directly to the main activity.
my MainActivity.java:
package com.defcomm.invento;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.defcomm.invento.NavigationDrawerActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class INVENTO extends AppCompatActivity {
private Toolbar toolbar;
private CoordinatorLayout mCoordinator;
private CollapsingToolbarLayout mCollapsableLayout;
private NestedScrollView nestedScrollView;
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
mCoordinator= (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mCollapsableLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
toolbar= (Toolbar) findViewById(R.id.appbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mCollapsableLayout.setTitle(getResources().getString(R.string.app_name));
nestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
mCollapsableLayout.setExpandedTitleTextAppearance(R.style.ExpandedTitleTextAppearence);
mCollapsableLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.textColor));
NavigationDrawerActivity drawerFragment= (NavigationDrawerActivity) getSupportFragmentManager().
findFragmentById(R.id.navigation_drawer);
drawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawerlayout), toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_invento, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
my NavigationDrawer.java1:
package com.defcomm.invento;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.support.design.widget.CollapsingToolbarLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NavigationDrawerActivity extends Fragment implements MyAdapter.clickListener {
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mdrawerLayout;
private boolean mUserLearnedState;
private MyAdapter adapter;
private CoordinatorLayout mcoordinator;
private RecyclerView recyclerView;
private CollapsingToolbarLayout collapsingToolbarLayout;
View containerId;
public static final String file_pref_name = "Testpef";
public static final String KEY_USER_VALUE = "user_learned_drawer";
private boolean mfromSavedInstanceState;
public NavigationDrawerActivity() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedState = Boolean.valueOf(readPreference(getActivity(), KEY_USER_VALUE, "false"));
if (savedInstanceState != null) {
mfromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout=inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView= (RecyclerView) layout.findViewById(R.id.recycler);
adapter=new MyAdapter(getActivity(),getdata());
adapter.setClicklistener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<ListItems> getdata(){
List<ListItems> nav_data=new ArrayList<>();
int[] icons={R.drawable.variable,R.drawable.ignore};
String[] texts={"Coding","Hacking"};
for(int i=0;i<icons.length&&i<icons.length;i++){
ListItems current=new ListItems();
current.iconId=icons[i];
current.IconName=texts[i];
nav_data.add(current);
}
return nav_data;
}
public void setUp(final int fragmentId, DrawerLayout drawerlayout, final Toolbar toolbar) {
mdrawerLayout = drawerlayout;
containerId = getActivity().findViewById(fragmentId);
mdrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar,
R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedState) {
mUserLearnedState = true;
saveToPreference(getActivity(), KEY_USER_VALUE, mUserLearnedState + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (slideOffset < 0.5f) {
toolbar.setAlpha(1 - slideOffset);
}
}
};
if (!mUserLearnedState && !mfromSavedInstanceState) {
mdrawerLayout.openDrawer(containerId);
}
mdrawerLayout.setDrawerListener(mdrawerToggle);
mdrawerLayout.post(new Runnable() {
#Override
public void run() {
mdrawerToggle.syncState();
}
});
}
public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
SharedPreferences shared = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readPreference(Context context, String preferenceName, String defaultValue) {
SharedPreferences share = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
return share.getString(preferenceName, defaultValue);
}
#Override
public void ItemCLick(View view, int position) {
if(position==0){
startActivity(new Intent(getActivity(),Coding.class));
}
if(position==1){
startActivity(new Intent(getActivity(),Hacking.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.defcomm.invento" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".INVENTO"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Coding"
android:label="#string/title_activity_coding" >
</activity>
<activity
android:name=".Hacking"
android:label="#string/title_activity_hacking" >
</activity>
</application>
you can try this.
#Override
public void onBackPressed() {
startActivity(new Intent(this,MainActivity.class));
this.finish();
}
Try this
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This will close all other activities and start MainActivity
This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).
DrawerLayout drawer...
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(drawer.isDrawerOpen(Gravity.LEFT)){
drawer.closeDrawer(Gravity.LEFT);
startActivity(new Intent(CurrentActivity.this , MainActivity.class))
finish();
}else{
super.onBackPressed();
}
}
How can i switch activity using Button? this is my problem:
package net.example.finals;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnClickListener {
Button bq;
Button bw;
Button be;
Button br;
Button bt;
Button by;
Button bu;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second,
container, false);
bq=(Button)rootView.findViewById(R.id.btn1);
bq.setOnClickListener(this);
bw=(Button)rootView.findViewById(R.id.btn2);
bw.setOnClickListener(this);
be=(Button)rootView.findViewById(R.id.btn3);
be.setOnClickListener(this);
br=(Button)rootView.findViewById(R.id.btn4);
br.setOnClickListener(this);
bt=(Button)rootView.findViewById(R.id.btn5);
bt.setOnClickListener(this);
by=(Button)rootView.findViewById(R.id.btn6);
by.setOnClickListener(this);
bu=(Button)rootView.findViewById(R.id.btn7);
bu.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//i dont know what to put here
case R.id.btn1:
if(bq.callOnClick()==true){
Intent myOwnIntent = new Intent(getActivity(), Second.class);
startActivity(myOwnIntent);
}
break;
}
}
}
Why did you use "if(bq.callOnClick()==true)" this?
Android use a lots of java code, first you need to learn java properly.
AND Google too
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.btn1:
Intent myOwnIntent = new Intent(YourActivityName.this, Second.class);
startActivity(myOwnIntent);
break;
}
}
Try this one.
How to start new activity on button click
Start another activity by clicking a button
Android eclipse how to start a new activity on button click
I am working on two app, ApplicationA and ApplicationB, ApplicationA send String to ApplicationB,and i am display the receiving string on ApplicationB Activity.now everthing is working fine,when i Click on a Button from ApplicationA and want to send a string to ApplicationB,there is popup appear and i am select the ApplicationB from this popup,i want when i click on Button from ApplicationA the popup does not appear and directly my ApplicationB open and display the recieving string,also i want to perform this task in a background services,how i can achieve this?
My ApplicationA MAinActivity:
package com.example.applicationa;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button sendstring;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendstring = (Button) findViewById(R.id.sendstring);
sendstring.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
// startActivity(sendIntent);
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my ApplicationA Screen Shot:
When click on button the popup will appear and i am selecting ApplicationB from this popup:
This is my ApplicationB MainActivty:
package com.example.applicationb;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text_recieve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_recieve = (TextView) findViewById(R.id.text_recieve);
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
text_recieve.setText(sharedText);
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and This is my ApplicationB menifast file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicationb"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and this the ApplicationB screen shot when i am Receive the the string from ApplicationA:
Note:-
now i want to when i click on button from ApplicationA,complete process will be perform in background services,and when background services is done,then my ApplicationB activity is open with the receiving string,how i can achieve this through services,when click on button the popup will not appear to the user,please some one help me out,Thanks Alot in advance
In the intent to start your other app you have to mention its package name like:
intent.setClassName("com.farhan.appb",
"com.farhan.appb.MainActivity");
I have solved my Problem:
my MainActivity from ApplicationA:
package com.example.applicationa;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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 sendstring;
EditText edit_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startService(new Intent(MainActivity.this, MyService.class));
edit_text = (EditText) findViewById(R.id.edit_text);
sendstring = (Button) findViewById(R.id.sendstring);
sendstring.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(MainActivity.this, MyService.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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Background Service class:
package com.example.applicationa;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
String et_name;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
// et_name = getIntent().getStringExtra("dealer_id");
/*
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
// startActivity(sendIntent);
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));*/
/*player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false);*/ // Set looping
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(intent != null){
et_name = intent.getStringExtra("et_name");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
// player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "" + et_name, Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
Intent sendIntent = new Intent();
sendIntent.setClassName("com.example.applicationb",
"com.example.applicationb.MainActivity");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
startActivity(sendIntent);
// player.start();
}
}
This question already has an answer here:
Android adding new xml and class
(1 answer)
Closed 8 years ago.
This could be perceived as a silly question, but I am very new to Android.
I am making an app and I have added an info Activity, I have an info button on my main page and want to go to the info activity when I click it..
I'm actually not sure how to go about it.
this is the xml for the Button:
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#FFFFFF"
android:text="#string/info_btn" />
Do I add the code in the main activity, the intro activity or the xml?
This is my main activity
package ie.gmit.project;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void openSite(View v){
Uri uri = Uri.parse("http://gmitsu.ie/clubssocs/directory.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
UPDATED:
This has the updated code, and runs error free... but the button still will not go to the new activity when I run it.
package ie.gmit.project;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
private Button button2;//this is a bad name
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2= (Button) findViewById(R.id.button2);//find the button
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), IntroActivity.class);
startActivity(i);
// finish();//if you want to close main activity after start info activity
}});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void openSite(View v){
Uri uri = Uri.parse("http://gmitsu.ie/clubssocs/directory.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ie.gmit.project"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="ie.gmit.project.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ie.gmit.project.IntroActivity"
android:label="#string/title_activity_intro" >
</activity>
</application>
</manifest>
try this
public class MainActivity extends Activity {
private Button button2;//this is a bad name
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
button2= (Button) findViewById(R.id.button2);//find the button
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), InfoActivity.class);
startActivity(i);
finish();//if you want to close main activity after start info activity
});
}
declare in manifest intro activity in manifest
<activity
android:name=".IntroActivity"
android:label="Intro Activity"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
if this does not work you can add entries to the log to see if the data are assigning well, such as:
#Override
public void onClick(View v) {
Log.i("MyLog", "Im here!");
Intent i = new Intent(v.getContext(), InfoActivity.class);
startActivity(i);
finish();//if you want to close main activity after start info activity
});