The method getApplicationContext() is undefined - fragment issues - java

I am getting the following errors:
The method getApplicationContext() is undefined
The method findViewById(int) is undefined for the type Fragment1
These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.
Any help would be greatly appreciated.
Thanks in advance.
Below is the code
public class Fragment1 extends Fragment {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
String userGender = ParseUser.getCurrentUser().getString("Gender");
String activityName = ParseUser.getCurrentUser().getString("ActivityName");
Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");
String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
Number userage = ParseUser.getCurrentUser().getNumber("Age");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null){
return null;
}
return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
container,false);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
// query.whereEqualTo("ActivityName",userActivitySelectionName);
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
// users with Gender = currentUser.Looking_Gender
query.whereEqualTo("Gender", userLookingGender);
// users with Looking_Gender = currentUser.Gender
query.whereEqualTo("Looking_Gender", userGender);
query.setLimit(1);
query.whereEqualTo("ActivityName", activityName);
query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage);
query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage);
// query.whereWithinKilometers("Maximum_Distance", point, maxDistance)
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).get("Name").toString());
names.add(userList.get(i).get("Headline").toString());
names.add(userList.get(i).get("Age").toString());
// names.add(userList.get(i).getParseObject("ProfilePicture").;
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("Name", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Update
Unreachable code error for setConversationList
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null){
return null;
}
return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
container,false);
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
Update
Upon launching the activity, I received the following message:
08-15 14:52:16.365: E/AndroidRuntime(3332): FATAL EXCEPTION: main
08-15 14:52:16.365: E/AndroidRuntime(3332): Process: com.dooba.beta, PID: 3332
08-15 14:52:16.365: E/AndroidRuntime(3332): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.usermatch}: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Handler.dispatchMessage(Handler.java:102)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Looper.loop(Looper.java:136)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invokeNative(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invoke(Method.java:515)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 14:52:16.365: E/AndroidRuntime(3332): at dalvik.system.NativeStart.main(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): Caused by: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.initialisePaging(usermatch.java:32)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.onCreate(usermatch.java:20)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Activity.performCreate(Activity.java:5231)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-15 14:52:16.365: E/AndroidRuntime(3332): ... 11 more
Below is the activity page that calls for the fragment
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class usermatch extends FragmentActivity {
private PageAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
initialisePaging();
}
private void initialisePaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mood, 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);
}
}
Update 2
Below is the message I receive in logcat
08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main
08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974
08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.dooba.beta.Fragment1$1.done(Fragment1.java:108)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:45)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:1)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.Parse$6$1.run(Parse.java:888)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.handleCallback(Handler.java:733)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.dispatchMessage(Handler.java:95)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Looper.loop(Looper.java:136)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invokeNative(Native Method)
08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invoke(Method.java:515)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 17:42:28.863: E/AndroidRuntime(4974): at dalvik.system.NativeStart.main(Native Method)

You can get the activity that contains the fragment with getActivity().
Therefore getActivity().getApplicationContext() would work.
getActivity().findViewById(int) would also work.
Make sure, though, you don't use getActivity() prior to onActivityCreated(), since it would return null prior to that.

Change
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
to
Intent intent = new Intent(getActivity(), LoginActivity.class);

you can access context from onAttach() like below example
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}

Related

Android - How to make an intent work from inside a ListView using a custom ArrayAdapter

I have this problem that whenever i click on the listView OnItemClick method it always crashes when it is trying to reach another intent down below i leave some code.
public class SelectFichas extends AppCompatActivity {
TextView tv;
ListView lv;
RecyclerView.LayoutManager mLayoutManager;
ImageButton btn1;
ArrayList<Ficha> slFichas;
List<Ficha> ftchArray;
DBHelper db;
MyAdapter aAdapt = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_ficha);
btn1 = (ImageButton) (findViewById(R.id.rg));
lv = (ListView) (findViewById(R.id.lv1));
db = new DBHelper(this);
try {
//Verificamos que la base de datos no este vacia
if (!db.isEmpty()) {
ftchArray = db.getAllFichas();
slFichas = new ArrayList<Ficha>();
for (Ficha fi : ftchArray) {
slFichas.add(fi);
}
// mAdapter = new MyAdapter(ftchArray,getApplication());
aAdapt = new MyAdapter(SelectFichas.this,0,slFichas);
View header = getLayoutInflater().inflate(R.layout.list_header, null);
lv.addHeaderView(header);
lv.setAdapter(aAdapt);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id) {
Ficha fi = (Ficha) aAdapt.getItem(position-1);
String sel = fi.getPreg();
String[] opc = {"Actualizar", "Borrar", "Adivinar", "Atras"};
Toast.makeText(getApplicationContext(), "Usted selecciono " +sel, Toast.LENGTH_SHORT).show();
final Intent intent = new Intent(SelectFichas.this,UpdFicha.class);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
}
}, 2000);
I also used a custom ArrayAdapter for my ListView is that influencing, in case i will leave some code about the adapter below.
public class MyAdapter extends ArrayAdapter<Ficha> {
private Context context;
private ArrayList<Ficha> ficha;
public MyAdapter(Context context, int resource, ArrayList<Ficha> objects) {
super(context, resource, objects);
this.context = context;
this.ficha = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
Ficha fi = ficha.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_items, parent,false);
RelativeLayout rv = (RelativeLayout)(view.findViewById(R.id.relativeLayout));
TextView id = (TextView)view.findViewById(R.id.id_view);
TextView preg = (TextView)view.findViewById(R.id.preg_view);
TextView ans = (TextView) view.findViewById(R.id.answer_view);
id.setText(String.valueOf(fi.getId()));
preg.setText(fi.getPreg());
ans.setText(fi.getRes());
return view;
}
}
Here is my Logcat EDITED
2-05 11:52:06.886 5997-5997/com.giamp.fichas W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x9ccbcb20)
12-05 11:52:06.886 5997-5997/com.giamp.fichas E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.giamp.fichas, PID: 5997
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
at android.widget.Spinner.onMeasure(Spinner.java:482)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362) 
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193) 
at android.widget.Spinner.onMeasure(Spinner.java:482) 
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416) 
at android.view.View.measure(View.java:16497) 
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719) 
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404) 
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291) 
at android.view.View.measure(View.java:16497) 
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916) 
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113) 
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295) 
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000) 
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) 
at android.view.Choreographer.doCallbacks(Choreographer.java:574) 
at android.view.Choreographer.doFrame(Choreographer.java:544) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515)
AdapterView<?> parent is not an Adapter, but it is a ViewGroup.
change
ArrayAdapter<Ficha> aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
to
final MyAdapter aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
and
Ficha fi = (Ficha) parent.getItemAtPosition(position);
to
Ficha fi = (Ficha) aAdapt.getItem(position);

I am trying to navigate to multiple activities using intents and i am getting a run time exception, I am a beginner with eclipse , so please guide me

MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.

Volley Request Queue NullPointerException

I am trying to use the Volley library to query an xml api on the web with a search query provided by the user through a SearchWidget.
Whenever I enter a search string, the app crashes with a NullPointerException on adding the StringRequest to the RequestQueue.
Why is this happening?
I am already using Volley with a singleton pattern, as recommended in the Android Developer Guide.
Here is my search() function in the MainActivity.
public static final String TAG = "MYAPPTAG"
private RequestQueue mRequestQueue;
...
protected void onCreate(Bundle savedInstanceState) {
...
// Handle search intent
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
}
...
private void search(String query) {
String xml = null;
String url = "http://www.acme.com/example.php?query=" + query;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
stringRequest.setTag(TAG);
mRequestQueue
.add(stringRequest); // the exception fires here
}
...
See below for the stack trace.
02-22 23:08:50.636 9856-9856/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 9856
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.search(MainActivity.java:121)
at com.example.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
You are firing off a search before you've set the requestqueue from singleton.
So onCreate, you check for the Intent and then start a search before you've got a handle on the volley singleton and, in turn, the requestqueue. Try moving the volley code before the Intent check, like this:
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}

Fragment is trying to cast to activity

I know this answer is probably simple but i cannot figure it out. I am modifying example code for a project and keep getting a ClassCastException when i try to launch the app. Says that ListActivityFragment cannot be cast to android.app.Activity. What im not understanding(which is probably the simple part) is why its trying to cast it onto an activity when my main is a fragmentactivity. I know the code is rough, still trying to finish it up but cant get past this.
FragmentActivity
public class MainActivity extends FragmentActivity {
private boolean isLargeScreen = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.normal_screen_layout) != null) {
isLargeScreen = false;
ListActivityFragment listActivityFragment = new ListActivityFragment();
listActivityFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.normal_screen_layout, listActivityFragment)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addItem:
ListActivityFragment newFragment = new ListActivityFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.normal_screen_layout, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
}
ListActivity
public class ListActivityFragment extends ListFragment implements
OnClickListener {
private ArrayList<String> items = new ArrayList<String>();
private ListView listView;
private View outerView;
private Button deleteButton;
private ListActivityListener listener;
public interface ListActivityListener {
public void meetingAdded();
}
public ListActivityFragment() {
}
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (ListActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
outerView = inflater.inflate(R.layout.list_of_meetings, container,
false);
listView = (ListView) outerView.findViewById(R.id.listView1);
deleteButton = (Button) outerView.findViewById(R.id.deleteButton);
createList();
return outerView;
}
public void createList() {
items.clear();
Iterator<Items> iterator = ItemCollection.Instance().iterator();
while (iterator.hasNext()) {
items.add(iterator.next().toString());
}
listView.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items));
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
ListView listView = getListView();
for (int index = 0; index < listView.getChildCount(); index++) {
View viewGroup = listView.getChildAt(index);
CheckBox checkBox = (CheckBox) viewGroup
.findViewById(R.id.itemSelectCheckBox);
if (checkBox.isChecked()) {
TextView textView = (TextView) viewGroup
.findViewById(R.id.productTextView);
int key = (Integer) textView.getTag();
ItemCollection.Instance().delete(key);
}
}
createList();
}
#Override
public void onStart() {
super.onStart();
}
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
}
}
And heres the Logcat
07-15 01:59:50.710: E/AndroidRuntime(878): FATAL EXCEPTION: main
07-15 01:59:50.710: E/AndroidRuntime(878): Process: com.example.assignment5, PID: 878
07-15 01:59:50.710: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.assignment5/com.example.assignment5.ListActivityFragment}: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 01:59:50.710: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): Caused by: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-15 01:59:50.710: E/AndroidRuntime(878): ... 11 more
07-15 01:59:51.160: E/NetdConnector(383): NDC Command {65 bandwidth setiquota eth0 9223372036854775807} took too long (1117ms)
Caused by: java.lang.ClassCastException:
com.example.assignment5.ListActivityFragment cannot be cast to
android.app.Activity 07-15 01:59:50.710: E/AndroidRuntime(878):
As the error says -
ListActivityFragment is not an activity. So you are trying to access it just like an activity.
Make sure you haven't declared ListActivityFragment in the manifest. In your manifest if you made an entry for the fragment then that's wrong.
Also make sure that you haven't used startActivity for the fragment. Because this is done for activity class and not for fragment class.

Send Data from one Activity to another - not Working

I have a TO DO List, and when I check the checkbox in one Activity I want the CheckBox and the text that is next to the Checkbox to go to another Activity. this is my Adapter:
public class MyItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyItemAdapter(Context context, String[] values) {
super(context, R.layout.item_list, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list, parent, false);
CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
textView.setText(values[position]);
return rowView;
}
public static SparseBooleanArray getCheckedItemPositions() {
// TODO Auto-generated method stub
return null;
}
public static void remove(Object pos) {
// TODO Auto-generated method stub
}
public void changeData(String[] items) {
// TODO Auto-generated method stub
}
public static void setAdapter(MyItemAdapter mAdapter) {
// TODO Auto-generated method stub
}
This is my First Activity code:
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
Bundle extras = new Bundle();
extras.putString("status", "Data Recived");
intent.putExtras(extras);
startActivity(intent);
}
});
}
This is my Second Activity code:
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
And Finaly this is my Log cat:
02-18 10:33:24.779: D/AndroidRuntime(1575): Shutting down VM
02-18 10:33:24.779: W/dalvikvm(1575): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 10:33:24.789: E/AndroidRuntime(1575): FATAL EXCEPTION: main
02-18 10:33:24.789: E/AndroidRuntime(1575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Stanton.quicktodolist/com.Stanton.quicktodolist.MainActivity}: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Looper.loop(Looper.java:130)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 10:33:24.789: E/AndroidRuntime(1575): at dalvik.system.NativeStart.main(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): Caused by: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 10:33:24.789: E/AndroidRuntime(1575): ... 11 more
Please Help me
This line of your stacktrace
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
points you to the error. Line 70 in the MainActivity causes a null pointer. It is often helpful to study and understand stacktraces. If you cannot figure it out yourself, show us the onCreate method of the MainActivity.
I believe that you replace the intent extra by the bundle extra just try this code and let me know pelase
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
//Bundle extras = new Bundle();
// extras.putString("status", "Data Recived");
intent.putExtras("status", "Data Recived");
startActivity(intent);
}
});
}
And the int the second activity
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
// Bundle bundle = intent.getExtras();
String status = intent.getStringExtra("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();

Categories