Android GridView Adapter with AsyncTask - java

I parse XML from web and I want to put this data to GridView in other activity, can you help me?
My first activity:
public class HomeScreenActivity extends Activity {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
Intent intent = new Intent(this, TopArtistsScreen.class);
intent.putExtra("username", username);
new DownloadXmlTask(this, HomeScreenActivity.this)
.execute("URL");
startActivity(intent);
}
My AsyncTask
public class DownloadXmlTask extends AsyncTask<String, Void, List<Artist>> {
#Override
protected void onPostExecute(List<Artist> result) {
progressDialog.dismiss();
gridView.setAdapter(new TopArtistsImageAdapter(context, result));
}
TopArtistsImageAdapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView==null) {
view = inflater.inflate(R.layout.items, null);
}
TextView textView = (TextView) view.findViewById(R.id.grid_item_name);
ImageView imageView = (ImageView) view.findViewById(R.id.grid_item_image);
textView.setText(artistsList.get(position).getName());
imageLoader.DisplayImage(artistsList.get(position).getImage(), imageView);
return view;
}
PS I shoud start another activity only after downloading all information

I shoud start another activity only after downloading all information
=> Make changes as below:
1) Only execute your AsyncTask on button click
new DownloadXmlTask(this, HomeScreenActivity.this).execute("URL");
2) Start Activity inside onPostExecute() method of your AsyncTask:
Intent intent = new Intent(HomeScreenActivity.this, TopArtistsScreen.class);
intent.putExtra("username", username);
startActivity(intent);

Related

How to go to another activity in Fragments | Android Studio

Need to create a button to go to a new activity in Fragments. I tried with the following code but its not working, This is my code,
public class UserFragment extends Fragment {
Button mTextuserinfo;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user,container,false);
mTextuserinfo = (Button) findViewById(R.id.userinfo_user);
mTextuserinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UserFragment.this, userinformation.class);
startActivity(i);
}
});
return view;
}
}
Use this in your onClick.
Intent i = new Intent(getActivity(), userinformation.class);
startActivity(i);
Also define your button like this:
mTextuserinfo = view.findViewById(R.id.userinfo_user);

Open activity from fragment instantly closed

Hello I want to move to another activity from my fragment. I ve tried almost every solution which I found, but after I press button my app is instantly closed. I am new in java, and i guess i need some help.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
Intent intent;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
final Button btn = (Button) rootView.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
I'm assuming from this line:
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
That you're trying to launch a Fragment, not an Activity. In order to transition to another Fragment, replace your Intent with:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getFragmentManager()
.beginTransaction()
.replace(...) //Or add, depends on your use case
.commit();
}
});

How can i passing data from recyclerview to fragment

I follow a youtube tutorial to write an application. this codes is a part of my recyclerViewAdapter
vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
TextView dialog_detail_tv = (TextView) myDialog.findViewById(R.id.dialog_detail);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
dialog_detail_tv.setText(mData.get(vHolder.getAdapterPosition()).getDetail());
Toast.makeText(mContext, "Test Click" + String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
Button dialog_add_tv = (Button) myDialog.findViewById(R.id.dialog_add);
dialog_add_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText dialog_quantity_tv = (EditText) myDialog.findViewById(R.id.dialog_quantity);
quantity = dialog_quantity_tv.getText().toString();
name = mData.get(vHolder.getAdapterPosition()).getName()+"\n";
price = mData.get(vHolder.getAdapterPosition()).getPhone();
Intent i = new
Intent(getActivity(),FragmentFav.class);
Bundle bundle = new Bundle();
bundle.putString("choices",choices);
bundle.putDouble("price",price);
i.putExtras(bundle);
startActivity(i);
}
});
}
});
return vHolder;
}
I want to Clicking the dialog_add_tv Button to pass the data to the fragment.class
public class FragmentFav extends Fragment {
View v;
public FragmentFav() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.call_fragment, container, false);
return v;
}
}
I try many times by using intent still happen error.
Using intent you can't open fragment, use below code for open fragment and also pass data to fragment
// define a framelayout in activity xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"></FrameLayout>
// then write below code on the click of dialog_add_tv button
Bundle bundle = new Bundle();
bundle.putString("choices",choices);
bundle.putDouble("price",price);
FragmentFav frgFav=new FragmentFav();
frgFav.setArguments(bundle);
FragmentTransaction fragmentTrasaction=getFragmentManager().beginTransaction();
fragmentTrasaction.add(R.id.fragment_container,frgFav,"frg");
fragmentTrasaction.commit();
// then get data in fragment like this
String choice=getArguments().getString("choices");
String price=getArguments().getString("price");
Here are the step you can follow and implement what you need
Step 1:
Create an interface between adapter and fragment
Step 2:
Implement an interface in Adapter like this:
vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProfileItemClickListener.itemContact(v);
}
// aka Pass the whole view through an interface
Step 3:
In an interface, class add this method
void itemContact(View mView);
Step 4:
Implement an interface in Fragment:
Where you will obtain an override method and perform your operation there
#Override
public void itemContact(ImageView mProfileImageView) {
Your code here
}
You can handle callback properly while passing data between the views.

How to open an Image in new activity when clicked in viewpager?

I'm using viewpager to display the slideshow of the images but when I'm clicked on any one of the image it need to opened in new activity. Can anyone help me?
I'm displaying toast message when clicked on image but my actually requirement is to open the image in new activity.
The code is below:
class MyCustomPagerAdapter extends PagerAdapter{
private Context context;
private int images[];
private LayoutInflater layoutInflater;
public int i;
MyCustomPagerAdapter(Context context, int images[]) {
this.context = context;
this.images = images;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
View itemView = layoutInflater.inflate(R.layout.full_profile, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.expandedImage);
imageView.setImageResource(images[position]);
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ImageOpeningActivity.class);
intent.putExtra("MY_IMAGE", images[position]);
context.startActivity(intent);
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
ImageOpeningActivity.class
class ImageOpeningActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageopening);
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
if(getIntent()!=null){
int image = getIntent().getExtras().getInt("MY_IMAGE");
imageView.setImageResource(image);
}
}
}
although i changed my code i getting an error, the error is below.
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.vmax.kalyanam/com.vmax.kalyanam.ImageOpeningActivity}: java.lang.IllegalAccessException: java.lang.Class<com.vmax.kalyanam.ImageOpeningActivity> is not accessible from java.lang.Class<android.app.Instrumentation>
public class Full_profile extends Activity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayout;
//public String title = "KANDIBANDA ROJA";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_profile);
ViewPager viewPager;
int images[] = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.one
};
MyCustomPagerAdapter myCustomPagerAdapter;
viewPager = (ViewPager)findViewById(R.id.viewPager);
myCustomPagerAdapter = new MyCustomPagerAdapter(Full_profile.this, images);
viewPager.setAdapter(myCustomPagerAdapter);
put intent here in "listening to image click"
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,PhotoViewerActivity.class);
intent.putExtra("image", imageurl);
startActivity(intent);
}
});
public class PhotoViewerActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("image");
// you can show image from url using library like glide or picasso
}
#Override
protected int getLayoutResourceId() {
return R.layout.activity_photo_viewer;
}
#Override
public void onBackPressed() {
PhotoViewerActivity.this.finish();
}
}
First of all do this in your code instead of Toast. Comment out Toast and paste these lines.
Intent intent = new Intent(this, ImageOpeningActivity.class);
intent.putExtra("MY_IMAGE", images[position]);
context.startActivity(intent);
step2: Create activity with the name of ImageOpeningActivity and in its xml take a Imageview , let suppose its Id is myImageView then do following in your on create
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
if(getIntent()!=null){
int image = getIntent().getExtras().getInt("MY_IMAGE");
imageView.setImageResource(image);
}
I am supposing that your images[position] is integer array.
Like #Pratap said you can send image url from one activity to another. But if you wanted to pass image itself as bitmap follow this method.
Bitmap implements Parcelable, so you can pass it as intent extra.
Intent intent = new Intent(this, ImageDetailActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it in ImageDetailActivity by calling,
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Warning: Do not pass data more than 500Kb through Intent Refer this site
create new activity with imageview in xml layout and call this from your viewpager image onclick
Intent intent = new Intent(this, ImageDetailActivity.class);
intent.putExtra("image",images[i]);
startActivity(intent);
ImageDetailActivity.java
public class ImageDetailActivity extends AppCompatActivity {
Drawable imageDrawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
Intent intent = getIntent();
imageDrawable= getResources().getDrawable(intent.getIntExtra("image",-1));
imageView.setImageDrawable(imageDrawable);
}
}
Make sure you add this ImageDetailActivity to your android manifest file

Get onActivityResult when returning from startActivityForResult in Adapter

I am trying to return some data when a user clicks back from the Activity.
I am calling startActivityForResult from the adapter, but when I actually press back from the Activity, onActivityResult never seems to be called
Code is trimmed down for example
Fragment1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View mainView = inflater.inflate(R.layout.grid_view, container, false);
return mainView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.w(TAG, "in activity result");
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
}
Adapter
public Adapter(Context context, List<Item> objects) {
super(context, -1, objects);
this.context = context;
addAll(objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.grid_view_item, parent, false);
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
((Activity) context).((Activity) context).startActivityForResult(intent, 1);(intent, 1);
}
});
return view;
Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_view);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
denyEditPermission = extras.getBoolean("denyEditPermission");
}
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("denyEditPermission", denyEditPermission);
setResult(RESULT_OK, intent);
finish();
}
Since you use activity context to start the activity, you will get onActivityResult callback in activity, not in fragment. To get callback in fragment, you need to use fragment context/start activity in fagment itself. I would suggest interface approach to fix the issue here.Create an interface and implement it in your fragment and when the recommendationLayout is clicked, call the interface method from adapter so that you can handle the click event in fragment itself.
Something like,
Create an interface file -
public interface RecommendationClickListener {
public void onRecommendationClicked();
}
Fragment:
public class MyFragment extends Fragment implements RecommendationClickListener{
...
...
...
#Override
public void onRecommendationClicked() {
Intent intent = new Intent(getActivity(), NextActivity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mAdapter.setRecommendationClickListener(this);
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
Adapter:
private RecommendationClickListener mRecommendationClickListener;
public void setRecommendationClickListener(RecommendationClickListener recommendationClickListener) {
this.mRecommendationClickListener = recommendationClickListener;
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecommendationClickListener != null) {
mRecommendationClickListener.onRecommendationClicked();
}
}
});
The Broadcast solution is as follows:
In Fragment
Declare on top of the class
public final static String START_ACT = "com.yourcompanyname.appname.START_ACT";
private Radio radio;
On the createView initiate and register the receiver
//Initiate our receiver
radio = new Radio();
//Activate our recevier
getActivity().getApplicationContext().registerReceiver(radio, new IntentFilter(START_ACT));
Also in the fragment, create the receiver class and the mothod which calls the Activity
/**
* Receiver Class
* This setup checks for the incoming intent action to be able to
* attach more messages to one receiver.
*/
private class Radio extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(START_ACT)){
getDataFromActivity();
}
}
}
public void getDataFromActivity(){
Intent intent = new Intent(getActivity(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
After from anywhere in the application send message to our radio
context.sendBroadcast(new Intent(Fragment1.START_ACT));

Categories

Resources