How to get next activity when clicked from frag button - java

Hi i am trying to get my NextActivity when i press on Fab in my View 1
View 1 xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/Fbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="180dp"
android:clickable="true"
android:paddingRight="16dp"
android:paddingBottom="16dp"
/>
</RelativeLayout>,
View.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class View1 extends Fragment {
private FloatingActionButton mFab;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.view1, container, false);
mFab.findViewById(R.id.Fbutton);
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),NextActivity.class);
startActivity(intent);
}
});
return view;
}
}
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.floatingactionbutton.FloatingActionButton.findViewById(int)' on a null object reference
at com.example.myapplication.View1.onCreateView(View1.java:21)
i have tried
getContext()
View1.this
nothing worked

You haven't complete the floating button assigning.
Remove mFab.findViewById(R.id.Fbutton); this line.
Add
mFab = view.findViewById(R.id.Fbutton);
Here view is used to get the ID from the layout.

From the code that you posted most probably the problem is that you are not assigning the return value of findViewById(R.id.Fbutton); to the mFab.
mFab = findViewById(R.id.Fbutton);

Related

Unable to Display Toast in Fragment

Here I have added the Java And Xml File In which I just want to display a Toast when the user clicks on the button.
This is just to check whether the Fragment is working or not.
Here onClickListener is not working for me in the Fragment. Even setText on TextView was not working when I tried. I Think there is sometihing problem with the components or some problem between the connection of java and xml file
Setting.java
package com.example.dell.jsonexp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class setting extends Fragment {
BackgroundTask b;
String e;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.setting, container, false);
final Button logout= (Button) RootView.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Button Pressed",Toast.LENGTH_LONG).show();
}
});
return inflater.inflate(R.layout.setting, container, false);
}
}
setting.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:text="Logout" />
</RelativeLayout>
You are setting a click listener to a button that is never shown.
You need to return the rootView instead of inflating another view.
return rootView;
In a Fragment you cant access view components in onCreateView() method, You have to Override onViewCreated() method.
Please update your code as below.
package com.example.dell.jsonexp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class setting extends Fragment {
BackgroundTask b;
String e;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.setting, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button logout= (Button) view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Button Pressed",Toast.LENGTH_LONG).show();
}
});
}
}
Thanks!
You need to return
return RootView;
and for the Toast you have to write
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "Whatever you want here", Toast.LENGTH_SHORT).show();
}
});

I'm having problems with running the code on my device [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 4 years ago.
Here is my problem. Below is my class (Events.java) below it is the error. I continue to run my code on my phone but continue to get that error. I don't know what exactly the problem is and I don't know how to fix it. I tried everything I looked up but kept getting errors. Please help I'm a noob obviously.
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public ListView onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), AddEvent.class);
Uri currentVehicleUri = ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton) getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity context
EventContract.EventEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
This is the error
05-24 14:02:00.885 15627-15627/com.androidapp.restart E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 15627
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast
to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:47)
at com.androidapp.restart.Events.onCreateView(Events.java:31)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is the xml file (events.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidapp.restart.Events">
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/no_event_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="16dp"
android:gravity="center"
android:text="#string/no_cardetails"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
EDITED
Now I have change the xml to a Relative Layout, same issues, but here is another issue I found:
at android.app.Fragment.performCreateView(Fragment.java:2508)
Here is the section of the Fragment.java:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
This is an issue:
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
You try to inflate listview but inflater returns you a LinearLayout a parent of all views. You need inflate the LinearLayout instead of listview and this is causes to cast exception.
You are trying to cast a layout on a listview
add this #id into your LinearLayout and inflate it in your Activity
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/layout";
tools:context="com.delaroystudiuos.alarmreminder.MainActivity">
and then call it like this
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout, container, false);;
If you are trying to access your existing ListView item in the XML:
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
You will need to instead use:
View view = inflater.inflate(R.layout.nav_events, container, false);
eventListView = view.findViewById(R.id.list);

Error inflating class fragment, inflateexception

I am having error something its written like android view inflate exception error in inflating class fragment and its pointing to MainActivity.java class , I am trying to find but still no luck, as there is no error in android studio but error shows when running in virtual device.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ai_agamcompaq.flexible.MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.ai_agamcompaq.flexible.FragmentA"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp" />
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.ai_agamcompaq.flexible.FragmentB"
android:id="#+id/fragment2"
android:layout_below="#+id/fragment"
android:layout_alignStart="#+id/fragment"
android:layout_marginTop="39dp" />
</RelativeLayout>
MainActivity.java
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements Communicator{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(int i) {
FragmentManager manager=getFragmentManager();
FragmentB f2= (FragmentB) manager.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
FragmentA.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentA extends Fragment implements
AdapterView.OnItemClickListener {
ListView list;
Communicator communicator;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
communicator=(Communicator)getActivity();
list= (ListView) getActivity().findViewById(R.id.listView);
ArrayAdapter adapter=ArrayAdapter.createFromResource(getActivity(),R.array.titles,android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
communicator.respond(i);
}
FragmentB.java
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView text;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_b,container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView);
}
public void changedata(int i){
Resources res=getResources();
String[] description=res.getStringArray(R.array.description);
text.setText(description[i]);
}
}
Communicator.java
public interface Communicator {
public void respond(int i);
}
fragment_b.xml
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:id="#+id/editText" />
</LinearLayout>
fragment_a.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:id="#+id/listView" />
strings.xml
<resources>
<string name="app_name">flexible</string>
<string-array name="titles">
<item>one</item>
<item>two</item>
<item>three</item>
<item>four</item>
</string-array>
<string-array name="description">
<item>oneoneoneoneoneoneoneoneoneoneo</item>
<item>twotwotwotwotwotwotwotwotwotwo</item>
<item>threethreethreethreethreethreethr</item>
<item>fourfourfourfourfourfourfourfourfo</item>
</string-array>
</resources>
I am having error something its written like android view inflate exception error in inflating class fragment and its pointing to MainActivity.java class , I am trying to find but still no luck, as there is no error in android studio but error shows when running in virtual device.
try this way. bind your control inside oncreatview method for fragment A
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.change_pass_frag, container);
regmail=(EditText)view.findViewById(R.id.regemail);
oldpass=(EditText)view.findViewById(R.id.oldpass);
return view;
}
i got it , i have to inflate fragment_a
View view=inflater.inflate(R.layout.fragment_a,container,false);

Fragment in Android unnecessarily repeating more than once

Iam trying to keep a simple fragment with only one button.But it is coming 2 times like this
I had a linear layout and another nested linear layout in it.These are all present in activity_welcome.xml whose content is as follows :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99cc00"
android:orientation="vertical"
tools:context="com.acs.AfterLogin.WelcomeActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/replacable_container"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Iam trying to replace the replacable_container(Linear Layout) with the fragment whose java class is this :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.acs.AfterLogin.WelcomeActivity;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeFragment1 extends Fragment{
View v;
CardView cardView1,cardView2,cardView3;
CircleImageView userIcon;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return inflater.inflate(R.layout.welcome_fragment_1,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The xml content of fragment is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e0ebe5"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
</LinearLayout>
The operations like fragment transcation and all are contained in the mainactivity whose java code is this :
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.acs.AfterLogin.WelcomeFragments.WelcomeFragment1;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeActivity extends AppCompatActivity {
FragmentTransaction transaction;
WelcomeFragment1 frag1;
FragmentManager manager;
String imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
(new FragTask()).execute();
}
private class FragTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
transaction = manager.beginTransaction();
frag1 = new WelcomeFragment1();
transaction.replace(R.id.replacable_container, frag1, "welcome_1");
transaction.commit();
return null;
}
}
}
Thanks a lot in advance :)
Try to change this line
v=inflater.inflate(R.layout.welcome_fragment_1,container);
to
v=inflater.inflate(R.layout.welcome_fragment_1,container, false);
And return the inflated view. The boolean value indicates that you don't want to attach your view to container. Check this. Fragment will attach it later by itself.
Please return inflated view instead of inflating again in return statement.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return v;
}

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference - Bundle putExtra [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
The required output is that in 1st activity, there's a title, imageview and 3 buttons. When the image is clicked, new activity starts where same details are shown but this time only that post is shown(later along with comments). SO I need to pass the title and image details using bundle but my app crashes.
CustomAdapter.java code:
package com.example.swapsha96.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
class CustomAdapter extends ArrayAdapter<String> {
private final String[] itemname;
private final Integer[] imgid;
private final Context context;
public CustomAdapter(Context context, String[] resource, Integer[] imgid) {
super(context, R.layout.postcard, resource);
this.itemname=resource;
this.imgid=imgid;
this.context = context;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.postcard, parent, false);
TextView title = (TextView)view.findViewById(R.id.title);
ImageView post = (ImageView)view.findViewById(R.id.post);
Button plus1 = (Button)view.findViewById(R.id.plus1);
Button share = (Button)view.findViewById(R.id.share);
Button comment = (Button)view.findViewById(R.id.comment);
title.setText(itemname[position]);
post.setImageResource(imgid[position]);
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(), Post.class);
Bundle extras = new Bundle();
extras.putString("title",itemname[position]);
extras.putInt("post", imgid[position]);
intent.putExtras(extras);
parent.getContext().startActivity(intent);
}
});
return view;
}
}
Post.java code: (the activity class which is going to open next on image click)
package com.example.swapsha96.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
public class Post extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String titleValue = extras.getString("title");
Integer postValue = extras.getInt("post");
TextView title = (TextView)findViewById(R.id.title);
ImageView post = (ImageView)findViewById(R.id.post);
title.setText(titleValue);
post.setImageResource(postValue);
}
}
activity_post.xml post:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="#+id/postcard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.swapsha96.myapplication.Post"
android:background="#FFFFFF"
android:layout_margin="2dp"
android:adjustViewBounds="true">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
android:id="#+id/myScrollingContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:fillViewport="true">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal"
android:divider="#android:color/transparent"
android:dividerHeight="2dp" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
It throws the error that title.setText(titleValue); in 2nd code is a null object reference and hence unable to start the activity.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.swapsha96.myapplication/com.example.swapsha96.myapplication.Post}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
You haven't declared any TextView with id title in you layout. So you are unable to find that textview and hence title object is null.
Add TextView to your layout like this:
<TextView android:id="#+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" "/>

Categories

Resources