Android won't open new activity from listview - java

The app stops working when clicking on the first item on the list! I tried writing the code in a couple of different ways but it still won't work! What am I doing wrong??
package com.vogella.android.filmapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String [] filmArray = {"Harry Potter", "No time to die", "Finding Dory", "Spider-Man",
"The Avengers", "Little Women", "Dune"};
ListAdapter theAdapter = new MyAdapter(this,filmArray);
ListView film_list_view= findViewById(R.id.film_list_view);
film_list_view.setAdapter(theAdapter);
film_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
Intent intent = new Intent(view.getContext(), HarryPotter.class);
startActivity(intent);
}
}
});
}
}
Help?

Related

Notify adapter on item inserted in RoomDatabase and update the recyclerView

I am creating a notes app with java, i added room database to my app and when user saves a notes it adds it to database but doesn't shows in recyclerView immediately, when i reloads the app then it shows up, how and where should i insert notifyiteminserted so that recyclerView changes immediately
I have tried onResume Method but that results in app crash.
This is my MainActivity.
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static ArrayList<Notes> arrNotes;
#SuppressLint("StaticFieldLeak")
RecyclerViewAdapter adapter;
RecyclerView.LayoutManager layoutManager;
notesModelView modelView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper dbHelper = DatabaseHelper.getDatabase(this);
arrNotes = (ArrayList<Notes>) dbHelper.notesDao().getAllNotes();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
adapter = new RecyclerViewAdapter(this, arrNotes);
recyclerView.setAdapter(adapter);
//setting up recycler view
layoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
//Setting custom Toolbar
Toolbar toolbar1 = findViewById(R.id.toolbar);
setSupportActionBar(toolbar1);
//Moving from MainActivity to add_Notes Activity
Button button = findViewById(R.id.floatingActionButton);
button.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, addActivity.class);
startActivity(intent);
});
}
}
This is my add_Activity.
package com.example.keepnotes;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.Objects;
public class addActivity extends AppCompatActivity {
MainActivity mainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
Toolbar toolbar_add = findViewById(R.id.toolbar_add_activity);
setSupportActionBar(toolbar_add);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
toolbar_add.setNavigationIcon(R.drawable.back_button);
toolbar_add.setNavigationOnClickListener(view -> onBackPressed());
EditText titleText = findViewById(R.id.add_activity_title);
EditText bodyText = findViewById(R.id.add_activity_text);
Button saveBtn = findViewById(R.id.button);
DatabaseHelper database = DatabaseHelper.getDatabase(this);
saveBtn.setOnClickListener(view -> {
String titleBody = titleText.getText().toString();
String textBody = bodyText.getText().toString();
if (titleBody.equals("") && textBody.equals("")) {
Toast.makeText(addActivity.this, "Fields can't be empty",
Toast.LENGTH_LONG).show();
} else {
database.notesDao().addNotes(new Notes(titleBody, textBody));
finish();
}
});
}
}
How can i notify adapter the changes on each item add in database.
Here is my MainActivity after update to liveData.
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static ArrayList<Notes> arrNotes;
#SuppressLint("StaticFieldLeak")
RecyclerViewAdapter adapter;
RecyclerView.LayoutManager layoutManager;
notesModelView modelView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper dbHelper = DatabaseHelper.getDatabase(this);
modelView = new ViewModelProvider(this).get(notesModelView.class);
modelView.getAllNotes().observe(this, new Observer<List<Notes>>() {
#Override
public void onChanged(List<Notes> notes) {
arrNotes = (ArrayList<Notes>) notes;
}
});
arrNotes = (ArrayList<Notes>) dbHelper.notesDao().getAllNotes();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
adapter = new RecyclerViewAdapter(this, arrNotes);
recyclerView.setAdapter(adapter);
//setting up recycler view
layoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
//Setting custom Toolbar
Toolbar toolbar1 = findViewById(R.id.toolbar);
setSupportActionBar(toolbar1);
//Moving from MainActivity to add_Notes Activity
Button button = findViewById(R.id.floatingActionButton);
button.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, addActivity.class);
startActivity(intent);
});
}
}
this is Dao.
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
#Dao
public interface NotesDao {
#Query("SELECT * FROM notesTable")
List<Notes> getAllNotes();
#Query("SELECT * FROM notesTable")
LiveData<List<Notes>> findAllNotes();
#Insert
void addNotes(Notes note);
#Update
void updateNotes(Notes note);
#Delete
void deleteNotes(Notes note);
}
And here is my ViewModel
package com.example.keepnotes;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class notesModelView extends AndroidViewModel {
DatabaseHelper databaseHelper;
public notesModelView(#NonNull Application application) {
super(application);
databaseHelper = DatabaseHelper.getDatabase(application.getApplicationContext());
}
public LiveData<List<Notes>> getAllNotes() {
return databaseHelper.notesDao().findAllNotes();
}
}
Here is my RecyclerView adapter
package com.example.keepnotes;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
ArrayList<Notes> arrNotes;
DatabaseHelper databaseHelper;
RecyclerViewAdapter(Context context, ArrayList<Notes> arrNotes, DatabaseHelper databaseHelper) {
this.context = context;
this.arrNotes = arrNotes;
this.databaseHelper = databaseHelper;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(arrNotes.get(position).title);
holder.body.setText(arrNotes.get(position).text);
holder.index.setText(String.valueOf(position + 1));
holder.llView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setTitle("Delete view")
.setMessage("Are you sure to delete")
.setIcon(R.drawable.ic_baseline_delete_24)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
databaseHelper.notesDao().deleteNotes(new Notes(arrNotes.get(position).id,arrNotes.get(position).title,arrNotes.get(position).text));
notifyItemRemoved(position);
notifyItemRangeChanged(position, arrNotes.size());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.show();
return true;
}
});
}
#Override
public int getItemCount() {
return arrNotes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, body, index;
CardView llView;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.text_title_view);
body = itemView.findViewById(R.id.text_text_view);
index = itemView.findViewById(R.id.index);
llView = itemView.findViewById(R.id.card_View);
databaseHelper = DatabaseHelper.getDatabase(context);
}
}
}
It deletes the selected notes but also crashes immediately after confirming delete.
and it throws following error
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{535e3b3 position=5 id=-1, oldPos=4, pLpos:4 scrap [attachedScrap] tmpDetached not recyclable(1) no parent} androidx.recyclerview.widget.RecyclerView{11f4816 VFED..... ......ID 31,171-689,1048 #7f090165 app:id/recycler_view}, adapter:com.example.keepnotes.RecyclerViewAdapter#fd652a0, layout:androidx.recyclerview.widget.StaggeredGridLayoutManager#32e1e59, context:com.example.keepnotes.MainActivity#286bccd
Remove this two line
notifyItemRemoved(position);
notifyItemRangeChanged(position, arrNotes.size());
OLD ANSWER
First, if you use liveData you don't need to call the method
arrNotes = (ArrayList<Notes>) dbHelper.notesDao().getAllNotes();
just keep a reference to the adapter instance and whenever there is a change from liveData call the notifyDataSetChanged method.
adapter = new RecyclerViewAdapter(this,new List<Notes>());
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setAdapter(adapter);
modelView.getAllNotes().observe(this, new Observer<List<Notes>>() {
#Override
public void onChanged(List<Notes> notes) {
arrNotes.clear();
arrNotes.addAll(notes);
adapter.notifyDataSetChanged()
}
});
observe a LiveData object as it is not a LifecycleOwner
Use observeForever() on the LiveData, manually unregistering via removeObserver() when appropriate (onDestroy() of the service, if not sooner).
Bear in mind that standard service limitations apply here (e.g., services run for ~1 minute on Android 8.0+ unless they are foreground services), so it may be that you need to consider other approaches anyway. 🤞
Also you can read more in original post in here -> Link

how to set event for grid view by imageview

I'm newbie and just study Java around 1 month.
i'm trying to create group picture by grid view and if i click any picture then show for user alert dialog ask user want to delete picture or not. But somehow when i try to set event for grid view by image. i can't start up app. can help me find where is crash cause app can't start up.
package com.example.hi.gridviewhinhanh;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Danhsachhinhanh> manghinhanh;
HinhanhAdapter arrayAdapter;
GridView gridView;
ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridview);
manghinhanh = new ArrayList<>();
manghinhanh.add(new Danhsachhinhanh(R.drawable.chupanh));
manghinhanh.add(new Danhsachhinhanh(R.drawable.goidien));
manghinhanh.add(new Danhsachhinhanh(R.drawable.photoshop));
manghinhanh.add(new Danhsachhinhanh(R.drawable.quality));
manghinhanh.add(new Danhsachhinhanh(R.drawable.secutiry));
manghinhanh.add(new Danhsachhinhanh(R.drawable.signuptoday));
arrayAdapter = new HinhanhAdapter(MainActivity.this, manghinhanh);
gridView.setAdapter(arrayAdapter);
imgView = findViewById(R.id.imageviewHinhanh);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder hopthoai = new AlertDialog.Builder(MainActivity.this);
hopthoai.setTitle("Do you want to delete");
hopthoai.setMessage("Please confirm");
hopthoai.setIcon(R.mipmap.ic_launcher);
hopthoai.setCancelable(false);
hopthoai.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
hopthoai.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You choose No", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.hi.gridviewhinhanh;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class HinhanhAdapter extends BaseAdapter {
Context context;
ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList;
public HinhanhAdapter (Context context, ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList){
this.context = context;
this.danhsachhinhanhArrayList = danhsachhinhanhArrayList;
}
#Override
public int getCount() {
return danhsachhinhanhArrayList.size();
}
#Override
public Object getItem(int position) {
return danhsachhinhanhArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.dong_item_gridviewhinhanh,null);
ImageView imageView = convertView.findViewById(R.id.imageviewHinhanh);
Danhsachhinhanh danhsachhinhanh = (Danhsachhinhanh) getItem(position);
imageView.setImageResource(danhsachhinhanh.getHinhanh());
return convertView;
}
}
place you imageView clickListener in Adapter's getView() and check it again.
Becuase your imageView does not exist there. For more information read about adapter and recycleview.

cannot resolve method show(android.support.v4.app FragmentManager,java.lang.string)

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().

ActionBarSherlock and FragmentTabsPager

As a lot of people have been doing so far, I'm implementing the FragmentTabsPager into my app, which is using ActionBarSherlock 4.0. However, I'm lost.
Fragments, and all of Google's little ideas, plans and methods surrounding it, are confusing me. If anyone could take a look at my code and walk me through this, providing help in making it work, I would thank them a thousand times :D.
I have another project with a sort-of beginning for a ViewPager, but the Tabs just mix better, especially with them being in the ActionBar on landscape and tablets.
My code is all zipped up and ready to go over here:
http://dl.dropbox.com/u/21807195/Antonius%20College%202.zip
Thanks in advance!
I will show you my code that has a ViewPager, TabListener, and system of Fragments linked to each tab. It implements ABS, but as of yet, still crashes on Gingerbread and lower (works beautifully on ICS, though):
import java.util.ArrayList;
import library.DatabaseHandler;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
Log.v(TAG, (String)bar.getTabAt(0).getText());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
//Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
And here is what one fragment looks like:
package com.davekelley.polling;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MilitaryFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.militaryfragment, container, false);
}
}
My last note would that my code still has one other issue: individual fragments do not always reload their interface after the user press back (which results in removing the entire app from the screen, regardless which tab/fragment they are on, because I have no backStack). So that's what I'm working through now. I think once I have that sorted, I'll try to figure out why I still don't have Gingerbread execution functioning properly. Either way, I hope looking through this code helps you out.
Here is a fragment with some onClickListeners:
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends SherlockFragment {
Button loginButton;
Button registerButton;
Polling activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.loginfragment, container, false);
return v;
}
public void onResume() {
super.onResume();
Log.d("Econ", "onresume");
loginButton = (Button) getActivity().findViewById(R.id.loginButton);
loginButton.setOnClickListener(loginListener);
registerButton = (Button) getActivity().findViewById(R.id.registerButton);
registerButton.setOnClickListener(registerListener);
}
public OnClickListener loginListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(loginButton.getText().toString() == "Log Out") {
activity.loginReport(2);
loginButton.setText(R.string.login);
//Remove user from dB sqllite when I know how
}
else {
Log.v("LoginF", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging in...");
LoginTask loginTask = new LoginTask((Polling) getActivity(), progressDialog);
loginTask.execute();
}
}
};
public OnClickListener registerListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Register", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Registering new user...");
RegisterTask registerTask = new RegisterTask((Polling) getActivity(), progressDialog);
registerTask.execute();
}
};
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (Polling) activity;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onStart() {
super.onStart();
Log.d("Econ", "onstart");
}
public void onPause() {
super.onPause();Log.d("Econ", "onpause");
}
public void onStop() {
super.onStop();
Log.d("Econ", "onstop");
}
public void onDestroyView() {
super.onDestroyView();
Log.d("Econ", "ondestroyview");
}
public void onDestroy() {
super.onDestroy();
Log.d("Econ", "ondestroy");
}
public void onDetach() {
super.onDetach();
Log.d("Econ", "ondetach");
}
}
The loginTask objects that you see are actually classes that extend ASyncTask - they handle connecting to my server and registering/logging in.
I thought it would be helpful to add in one bit more of code. This is another one of my fragments, like LoginFragment, but it inflates a UI a little differently. Eventually, what you see in the while loop below, will head into an ASyncTask to acquire each question from the server, rather than the dummy string array you see:
public class EconFragment extends SherlockFragment {
private TableLayout questionContainer;
int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("Econ", "onCreateView");
View v = inflater.inflate(R.layout.econfragment, container, false);
questionContainer = (TableLayout) v.findViewById(R.id.questionContainer);
//bs
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
Log.v("econ", "while loop");
questionContainer.addView(tr);
pos++;
}
pos = 0;
return v;
}
I have ported the FragmentTabsPager Activity and associated Fragments from "Support4Demos" (Android Support library sample) to use ActionBarSherlock and true ActionBar Tabs. The sample includes an Activity that uses both a ViewPager and Tabs to switch between Fragments. The Fragments contain three kinds of ListViews. I've tested it from ICS down to Eclair (2.1). You can browse or download the code at http://code.google.com/p/sherlock-demo/.

switching activities using spinner

i have the below code and i need to fill in the if(pos == 1){??????????} so that i can switch activities when the first position in my spinner is selected. The name of my new acitivity is Route1.java.
How would i write the code to switch to Route1.java when position 1 is selected in my spinner.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.Manifest.permission;
public class MyOnItemSelectedListener extends Activity
implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (pos == 1) {
} else {
Toast.makeText(parent.getContext(),
"Your route is "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
the above class is used in this class
import java.lang.reflect.Array;
import android.R.array;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.AbsSpinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class cnycentro extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cnycentro);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.routes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
}
MyOnItemSelectedListener() doesn't need to be a separate class, and it definitely shouldn't inherit from Activity.
Change your code to something like this:
OnItemSelectedListener listener = new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
//do you really want 1 here or 0?
if (position == 1) {
view.getContext().startActivity(new Intent(view.getContext().getApplicationContext(),Route1.class));
}else{
Toast.makeText(parent.getContext(), "Your route is " +
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
spinner.setOnItemSelectedListener(listener);
You should read up on intents and more specifically explicit intents.
In order to launch explicitly a new activity (like one you created) the syntax is:
Intent newActivity = new Intent(this, Route1.class);
startActivity(newActivity);
Also be sure to add the new activity to the android manifest:
<activity android:name=".Route1"></activity>
Edit:
+1 for not extending Activity in your listener, instead simply write
public class MyOnItemSelectedListener implements OnItemSelectedListener {
....
}
You can write it this way if your Activity or Listener is too large and it would reduce readability to write it inline.

Categories

Resources