When I click on an image in our project, another image gets loaded. It works fine, but when I go back to the previous activity, and click on the same image, it doesn't get loaded.
This is the first activity which opens when app is active. This page will show grid of pictures
public class GentsActivity extends Fragment implements AdapterView.OnItemClickListener {
//Web api url
public static final String DATA_URL = "PHP LINK HERE";
//Tag values to read from json
public static final String TAG_IMAGE_URL = "small_image_url";
//GridView Object
private GridView gridView;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private SwipeRefreshLayout swipeContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
View view= inflater.inflate(R.layout.activity_gents, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
getData();
//swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
images = new ArrayList<>();
//Calling the getData method
/*swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
//Toast.makeText(this,"refresh ",Toast.LENGTH_SHORT).show();
Intent mIntent= new Intent(SareeActivity.this,SareeActivity.class);
startActivity(mIntent);
swipeContainer.setRefreshing(false);
}
});*/
return view;
}
private void getData(){
//Showing a progress dialog while our app fetches the data from url
//final ProgressDialog loading = ProgressDialog.show(this, "Please wait,","Fetching data.",false,false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
// loading.dismiss();
//Displaying our grid
showGrid(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showGrid(JSONArray jsonArray){
//Looping through all the elements of json array
for(int i = 0; i<jsonArray.length(); i++){
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
// Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+obj);
//getting image url and title from json object
images.add(obj.getString(TAG_IMAGE_URL));
Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+images);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Creating GridViewAdapter Object
//Adding adapter to gridview
GridViewAdapter gridViewAdapter = new GridViewAdapter(getContext(),images);
gridView.setAdapter(gridViewAdapter);
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String prompt = (String)adapterView.getItemAtPosition(i);
Intent mIntent= new Intent(getActivity(),LoadPhotoGents.class);
mIntent.putExtra("s",prompt);
startActivity(mIntent);
}
}
When I click on a particular photo, that single photo will open. The code is given below
public class LoadPhotoGents extends AppCompatActivity {
private String data, path;
private ImageView ivi;
public static final String DATA_URL = "PHP LINK HERE";
private static int id=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_photo_gents);
data = getIntent().getExtras().getString("s");
path = data.replace(".JPG", "big.JPG");
//Toast.makeText(this, "Path:" + path, Toast.LENGTH_LONG).show();
ivi = (ImageView) findViewById(R.id.fullImage);
Picasso.with(LoadPhotoGents.this).load(path).into(ivi);
getData();
ImageViewTouch img = (ImageViewTouch) findViewById(R.id.fullImage);
img.setBackgroundColor(Color.parseColor("#000000"));
ivi.buildDrawingCache();
Bitmap bmap=ivi.getDrawingCache();
//img.setFitToScreen(true);
img.setImageBitmap(bmap);
}
private void getData(){
String url=DATA_URL+data.trim();
StringRequest stringRequest=new StringRequest(url,new Response.Listener<String>(){
#Override
public void onResponse(String response){
showJSON(response);
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name= "";
try{
JSONArray jsonArray=new JSONArray(response);
//JSONArray result= jsonObject.getJSONArray("result");
JSONObject datas=jsonArray.getJSONObject(0);
name=datas.getString("description");
}catch(JSONException e){
Toast.makeText(this,"inside getData: "+name,Toast.LENGTH_SHORT).show();
}
}
}
This will definitely help you to debug the issue. In your code I can see that you are loading the image directly using Picasso.with().load().into() problem with this method is you do not know what is happening at the background.
You can do two things. First use Callback when you load the image into the ImageView as below
Picasso.with(LoadPhotoGents.this).load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Error Loading Image");
}
});
Above can be used to handle image loaded/not loaded scenario.
Now coming to the actual error while loading the image, you need to use a Picasso.Builder which has a listener which will help you know the actual error.
Build Picasso Builder as below
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener()
{
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception)
{
Timber.d(exception.getMessage());
}
});
Picasso pic = builder.build();
To Load the image do the following
pic.load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Image Load Error");
}
});
Ensure that path variable is not null or empty
Related
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java
public CollegeImageGrid imagegrid;
private static final String TAG = "CollegeGallery";
public GridView grid_image, grid_video;
public DatabaseReference ref;
private String collegeid;
private TextView moreimages, morevideos;
private String playlistid;
public void setPlayid(String playlistid) {
this.playlistid = playlistid;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_gallery);
ref = FirebaseDatabase.getInstance().getReference("collegedata");
//this will get the data from previous intent
collegeid = getIntent().getStringExtra("gallery");
grid_image = findViewById(R.id.grid_image);
// grid_video = findViewById(R.id.grid_video); //for grid view of videos
moreimages = findViewById(R.id.more_images);
morevideos = findViewById(R.id.more_videos);
//a list of string will be passed to imagegrid object
ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//object of College class to get getImageurls() which has the list of urls
College clg = dataSnapshot.getValue(College.class);
//setting the list to imagegrid, passing url from this activity to imageview.
imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
//setting adapter to grid with the list of urls
grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
//extracting playlist id
String playid = getYoutubeVideoId(clg.getVideourls());
//fragment code
YoutubeVideoList yt = new YoutubeVideoList();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
}
});
moreimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
image_in.putExtra("image",collegeid);
startActivity(image_in);
}
});
//will take to activity with only playlist video list fragment
morevideos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
}
});
}
//function to extract playlist id
public static String getYoutubeVideoId(String youtubeUrl) {
String video_id = "";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {
String expression = "^.*?(?:list)=(.*?)(?:&|$)";
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(1);
video_id = groupIndex1;
}
}
return video_id;
}
}
YoutubeVideoList.java(Fragment)
private static String ARG_Param1;
private static String id;
List<YoutubeVideoModel> vids;
Button btn;
YoutubeAdapter adapter;
RecyclerView recyclerView;
RecyclerView.LayoutManager manager;
String mparam1;
public YoutubeVideoList() {
}
//retrieving playlist id from the previous activity
public static YoutubeVideoList newInstance(String id) {
YoutubeVideoList yt = new YoutubeVideoList();
Bundle args = new Bundle();
args.putString(ARG_Param1, id);
yt.setArguments(args);
return yt;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mparam1 = getArguments().getString(ARG_Param1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
}
#Override
public void onViewCreated(View container, Bundle savedInstanceState) {
super.onViewCreated(container, savedInstanceState);
recyclerView = container.findViewById(R.id.vidReclycer);
manager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(false);
id = mparam1;
//right here, id has the playlist id
System.out.println("this is the playlist id------------------->"+id);
String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
//even url has the value but the list is not shown and id changes to null
System.out.println(url);
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
vids = new ArrayList<>();
try {
JSONObject mainObject = new JSONObject(response);
JSONArray itemArray = (JSONArray) mainObject.get("items");
for (int i = 0; i < itemArray.length(); i++) {
String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
vids.add(vid);
}
adapter = new YoutubeAdapter(getContext(), vids);
recyclerView.setAdapter(adapter);
recyclerView.getAdapter().notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("Error in request", error.getMessage());
}
});
queue.add(request);
}
}
```this is the image of my logcat. It prints id and url as required, but then it changes to null
Got the answer. there was a problem in sharing data between activity and fragment. the value was being set null twice, one before and one after the function call(i dont know why but). then instead of calling newInstance() i used bundle, checked if it is null or not in fragment class and then set the value of id.
CollgeGallery.java
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//object of College class to get getImageurls() which has the list of urls
College clg = dataSnapshot.getValue(College.class);
String playid = getYoutubeVideoId(clg.getVideourls());
//setting the list to imagegrid, passing url from this activity to imageview.
imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
//setting adapter to grid with the list of urls
grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
//extracting playlist id
// String playid = getYoutubeVideoId(clg.getVideourls());
//fragment code
setPlayid(playid);
Bundle bun = new Bundle();
YoutubeVideoList firstfrag = new YoutubeVideoList();
bun.putString("test", playid);
firstfrag.setArguments(bun);
getSupportFragmentManager().beginTransaction().add(R.id.youtube_frag, firstfrag).commit();
// FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
// tr.add(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
}```
**YoutubeVideoList.java**
```#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = this.getArguments();
if(args != null){
id = args.getString("test");
}
}```
Thanks everyone for your help. :)
In your CollegeGallery.java in place of:
yt.newInstance(playid)
write this
YoutubeVideoList.newInstance(playid)
Also remove the static String id from your YoutubeVideoList fragment if it's useless
Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
i'm trying to get the data from the database to fill the activity with them but i'm not getting anything this is the db code i have 2 Textvies 1 image view i'm trying to fill with the data i'm new to mobile programming so need help:
public void gettypedet(final int tid, final TextView ttitle, final ImageView timg, final TextView desc) {
String url = "http://192.168.0.114/mobileshop/product_typrbyid.php?id="+tid;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a json response from the provided URL.
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject prt) {
try {
String type=prt.getString("type");
int imgname=Integer.parseInt(prt.getString("imagename"));
String des=prt.getString("description");
ttitle.setText(type);
timg.setImageResource(imgname);
desc.setText(des);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(jsonRequest);
}
this is my php code i tested it and it's working so shouldn't be the problem:
<?php
require_once("connection.php");
$id=$_GET["id"];
$q="Select * from product_type where id='$id'";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_assoc($res)){
$types[]=$row;
}
echo (json_encode($types));
mysqli_free_result($res);
?>
this is the activity code here not sure if i did something wrong:
public class ptype_detail extends Activity {
int kposition,tposition,id;
TextView ttitle,tdes;
ImageView timg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptype_detail);
tposition=(Integer)getIntent().getExtras().get("tpos");
kposition=(Integer)getIntent().getExtras().get("kpos");
if (kposition==0)
id=tposition+5;
else if(kposition==1)
id=tposition+18;
else if (kposition==2)
id=tposition+20;
else
id=tposition;
ttitle=(TextView)findViewById(R.id.title) ;
tdes=(TextView)findViewById(R.id.typedes);
timg=(ImageView)findViewById(R.id.titleimage);
shop db=new shop(this);
db.gettypedet(id,ttitle,timg,tdes);
}
}
I have an Activity that receives and displays information from the web server and saves it to the database and, if it has already received the information once, it will read from the database.
There is no problem running the program, only when the user enters the activity and still does not receive the information from the server, exit the activity, in another Activity the application crashes.
This problem is to quit the activity because when staying in activity and loaded data completely, we have not any problems. also when reading data from the database we have not any problems.
How can stop receive data when the user quit the activity or solve this problem form another way.
This is my activity codes:
public class ShowProduct extends AppCompatActivity {
private RequestQueue mQueue;
private String id;
private Products products;
private DatabaseHelper databaseHelper;
private ProgressBar progressBar;
private Typeface IranSans,IranSansBold;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_product);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
databaseHelper = new DatabaseHelper(this);
products = new Products();
progressBar = (ProgressBar)findViewById(R.id.progressBar);
IranSans = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb.ttf");
IranSansBold = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb_Bold.ttf");
Bundle extras = getIntent().getExtras();
id= extras.getString("id");
try {
if (databaseHelper.dbContentChecker(id)) {
if (connectionCheck() == false){
Intent intent = new Intent(this, NoInternetConnection.class);
startActivity(intent);
}
String url = "https://website.com/webserver/?id=" + id;
mQueue = Volley.newRequestQueue(this);
jsonParse(url);
} else {
products = databaseHelper.getOneProduct(id);
showFromDB(products);
}
}catch (Exception ex){
}
//footer set
Footer footer = new Footer();
footer.footerSet(ShowProduct.this, this);
}
private void showFromDB(Products products) {
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(products.getName());
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(products.getImage())
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(products.getContent()));
progressBar.setVisibility(View.GONE);
}
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("send");
JSONObject send = jsonArray.getJSONObject(0);
String title = send.getString("title");
String image = send.getString("image");
String content = send.getString("content");
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(title);
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(image)
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(content));
//Save in Database
try {
products.setProductId(id);
products.setName(title);
products.setImage(image);
products.setContent(content);
databaseHelper.editProduct(products);
}catch (Exception ex){
Toast.makeText(ShowProduct.this, "Error DB", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
//Toast.makeText(getApplicationContext(), ""+Temp , Toast.LENGTH_SHORT).show();
}
public boolean connectionCheck() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
}
First of all you should think about your architecture. Handling fetching data inside an Activity is not a good practice. Look at MVVM or MVP and try to put your data fetching logic in another layer.
For your specific problem you should try to cancle the request in the onStop() method of the Activity, see:
https://developer.android.com/training/volley/simple#cancel
I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.
I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.
I want to pass the other parameters to another activity, but i can't find out how to do that.
There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.
Here's my code
public class Tab1 extends Fragment {
private static final String ARG_PAGE = "arg_page";
private static final String STATE_MOVIES = "state movies";
private TextView txtResponse;
private String passID;
// Progress dialog
private ProgressDialog pDialog;
//private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
private String urlJsonImg = "http://image.tmdb.org/t/p/w342";
// temporary string to show the parsed response
private String jsonResponse = "";
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
private ArrayList<Movies> movies = new ArrayList<Movies>();
public Tab1() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MOVIES, movies);
}
public static Tab1 newInstance(int pageNumber){
Tab1 myFragment = new Tab1();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
try {
JSONArray result = response.getJSONArray("results");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < result.length(); i++){
JSONObject jsonObject = result.getJSONObject(i);
String id = jsonObject.getString("id");
String originalTitle = jsonObject.getString("original_title");
String releaseDate = jsonObject.getString("release_date");
String rating = jsonObject.getString("vote_average");
String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");
//jsonResponse = "";
jsonResponse += "ID: " + id + "\n\n";
jsonResponse += "Title: " + originalTitle + "\n\n";
jsonResponse += "Release Date: " + releaseDate + "\n\n";
jsonResponse += "Rating: " + rating + "\n\n";
}
//Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
parseResult(response);
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
//makeJsonArrayRequest();
// Calling the RecyclerView
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MovieAdapter(getActivity(),movies);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onMovieClick(View view, int position) {
Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();
**//what to do here?**
}
#Override
public void onMovieLongClick(View view, int position) {
Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
}
}));
makeJsonObjectRequest();
if (savedInstanceState!=null){
movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
mAdapter.notifyDataSetChanged();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tab_1, container, false);
return view;
}
private void parseResult(JSONObject response) {
try {
JSONArray arrayMovies = response.getJSONArray("results");
if (movies == null) {
movies = new ArrayList<Movies>();
}
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovies = arrayMovies.getJSONObject(i);
Movies item = new Movies();
item.setTitle(currentMovies.optString("original_title"));
item.setRating(currentMovies.optString("vote_average"));
item.setReleaseDate(currentMovies.optString("release_date"));
item.setId(currentMovies.optString("id"));
item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
movies.add(item);
mAdapter.notifyDataSetChanged();
//Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if (child!=null && clickListener!=null){
clickListener.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onMovieClick(View view, int position);
public void onMovieLongClick(View view, int position);
}
}
any help would be appreciated. Thanks!
You need to add those other two values to a bundle in the intent. So something like this:
Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)
And in your new activity just do this to retrieve:
String id = getIntent().getExtras().getString("movie_id_key");
Add them as extras in the intent with which you start the activity:
Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title);
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);
then pull them out in the onCreate of the other activity with
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.
In response to the comment below:
I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:
public void onClick(View v, int position){
Movie m = movies.get(position);
Intent intent = new Intent(v.getContext(), AnotherActivity.class);
intent.putExtra("my_movie_foo_key", m.getFoo());
intent.putExtra("my_movie_bar_key", m.getBar());
// etc.
v.getContext().startActivity(intent);
}
As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.