I am displaying image on recyclerView using modal class and adapter class file,
now I want to share images externally and download images on the phone.
but I tried a lot, I am not understanding how to get image URL in adapter file.
Please help me to find a solution.
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<Data> data;
private Context context;
public ImageAdapter(List<Data> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_design,parent,false);
return new ImageAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageButton share,download;
public ViewHolder(final View itemView) {
super(itemView);
imageView=(ImageView)itemView.findViewById(R.id.image);
share=(ImageButton)itemView.findViewById(R.id.share);
download=(ImageButton)itemView.findViewById(R.id.download);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "url", Toast.LENGTH_SHORT).show();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,"url here ");
shareIntent.setType("images/*");
context.startActivity(Intent.createChooser(shareIntent,"Send Via"));
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
}
thanks in advance.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
replace this with
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "url", Toast.LENGTH_SHORT).show();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,getLocalBitmapUri(getBitmapFromURL(data1.getImgUrl())));
shareIntent.setType("images/*");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(shareIntent,"Send Via"));
}
});
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
also add
public Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
and
fun getBitmapFromURL(strURL: String): Bitmap? {
return try {
val url = URL(strURL)
val connection = url.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val input = connection.inputStream
BitmapFactory.decodeStream(input)
} catch (e: IOException) {
e.printStackTrace()
null
}
}
You are getting image url from list, before share you have to Use Picasso to load the url into a Bitmap. after that
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shareItem(data1.getImgUrl())
}
});
public void shareItem(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
startActivity(Intent.createChooser(i, "Share Your Image"));
}
#Override public void onBitmapFailed(Drawable errorDrawable) { }
#Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
});
}
Convert Bitmap into URi:
public Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Hope it will help you!!
Related
I stored texts and images in firebase Storage, here's how my images path looks like in storage (1655329886202.jpg),
and here's ow they look in realtime database (https://firebasestorage.googleapis.com/v0/b/link-plus-8e35e.appspot.com/etc...)
I retrieved the texts but can't retrieve the images to the recycler view, I'm new to programming.
here is the code.
adapter :
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name);
imageView = itemView.findViewById(R.id.image_View_car);
}
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.dynamic_rv_item_layout, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Glide.with(mContext)
.load(uploadCurrent.getImageUrl())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
}
Main activity code
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
if (result != null) {
mImageView.setImageURI(result);
mImageUri = result;
}
}
}
);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(FireBaseImage.this, "Upload in progress", Toast.LENGTH_LONG).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(FireBaseImage.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getUploadSessionUri().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(FireBaseImage.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot Snapshot) {
double progress = (100.0 * Snapshot.getBytesTransferred() / Snapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
}
**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}
i have a problem and my problem is : when i kill the app or shutting down the device , all the information was erased and i can find it , first of all and what i want to do in the first place is: i want to check if this is the first time of the user to use this app or not , if that is the first time then save what he chosen in the sharedPreference xml and if not , then retrieve was chosen and show it , sorry for my bad english , it's not my mother tongue
this is the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quran);
readers= (CardView)findViewById(R.id.readers);
readers_name=(TextView)findViewById(R.id.readers_name);
rewaya=(TextView)findViewById(R.id.rewaya);
count=(TextView)findViewById(R.id.count);
Intent i = getIntent();
String txtData = i.getStringExtra("reciters_name");
String txtData1 = i.getStringExtra("reciters_rewaya");
String txtData2 = i.getStringExtra("reciters_count");
shareRef=getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor myedit = shareRef.edit();
boolean firstRun = shareRef.getBoolean("firstRun", true);
if(firstRun) {
myedit.clear();
myedit.putString("reciters", txtData);
myedit.putBoolean("firstRun", false);
myedit.putString("rewaya", txtData1);
myedit.putString("count", txtData2);
myedit.commit();
readers_name.setText(txtData);
rewaya.setText(txtData1);
count.setText(txtData2);
}else {
readers_name.setText(shareRef.getString("reciters", ""));
rewaya.setText(shareRef.getString("rewaya", ""));
count.setText(shareRef.getString("count", ""));
}
fav_suras=(RecyclerView)findViewById(R.id.fav_suras);
fav_suras.setLayoutManager(new LinearLayoutManager(this));
suras=(RecyclerView)findViewById(R.id.suras);
suras.setHasFixedSize(true);
suras.setLayoutManager(new LinearLayoutManager(this));
suras.setAdapter(Mquraan_adapter);
//mSuras_api = new ArrayList<>();
getRetrofit();
readers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (quran.this, Readers.class);
startActivity(intent);
}
});
}
public void getRetrofit() {
RequestInterface requestInterface = PostClient.getApiClient().create(RequestInterface.class);
Call<FomCombine> call = requestInterface.getPosts();
call.enqueue(new Callback <FomCombine>() {
#Override
public void onResponse(Call<FomCombine> call, retrofit2.Response <FomCombine> response) {
Toast.makeText(quran.this, "success", Toast.LENGTH_SHORT).show();
mSuras_api = response.body().getfom_combine();
Mquraan_adapter= new quran_adapter(quran.this, (ArrayList<suras_api>) mSuras_api);
suras.setAdapter(Mquraan_adapter);
Mquraan_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<FomCombine> call, Throwable t) {
Log.d("Tag", t.getMessage());
}
});
}}
this is the adapter
private Context mContext ;
private ArrayList<Reciters_api> mReciters_api;
public Reciters_adapter(Context context, ArrayList<Reciters_api> mmReciters_api) {
mContext=context;
mReciters_api=mmReciters_api;
}
#NonNull
#Override
public Reciters_adapter.ReadersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.single_row,parent,false);
return new ReadersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ReadersViewHolder holder, int position) {
Reciters_api reciters = mReciters_api.get(position);
String ID_number = reciters.getId1();
String Name =reciters.getName1();
String Rewaya = reciters.getRewaya();
String count =reciters.getCount();
holder.readers_names.setText(Name);
holder.countt.setText(count);
holder.rewayya.setText(Rewaya);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent Reciters = new Intent(context, quran.class);
Reciters.putExtra("reciters_name", Name);
Reciters.putExtra("reciters_rewaya", Rewaya);
Reciters.putExtra("reciters_count", count);
context.startActivity(Reciters);
}
});
}
#Override
public int getItemCount() {
return mReciters_api.size();
}
public class ReadersViewHolder extends RecyclerView.ViewHolder{
public TextView readers_names ,rewayya ,countt;
public ReadersViewHolder(#NonNull View itemView) {
super(itemView);
readers_names=itemView.findViewById(R.id.readers_names);
rewayya=itemView.findViewById(R.id.rewayya);
countt=itemView.findViewById(R.id.countt);
}
}
}
#Override
protected Bitmap doInBackground(String... imageurl)
{
try {
URL url = new URL(imageurl[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
return bitmap;
}catch (Exception e)
{
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(result!=null && imageReference!=null) {
ImageView imgview = (ImageView) imageReference.get();
if (imgview != null) {
imgview.setImageBitmap(bitmap);
}
}
}
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ItemData current=data.get(position);
try {
Mytask mytask=new Mytask(holder.getImageview());
mytask.execute(current.imageUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setClickListener(ClickListener clickListener)
{
this.clickListener=clickListener;
Bundle extras=new Bundle();
extras.putParcelable("image",bitmap);
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
icon=(ImageView)itemView.findViewById(R.id.item_icon);
}
public ImageView getImageview()
{
return icon;
}
public void onClick(View view)
{
if(clickListener!=null)
{
clickListener.itemClicked(view,getAdapterPosition());
}
}
}
public interface ClickListener{
public void itemClicked(View view,int position);
}
The above is the MyAdapter method. I want to pass the value of the bitmap to another activity in order to display the onItemClicked image from the RecyclerView list into another activity. My another question is that do I need to pass the intent stuff in my MainActivity's class method in
#override
Public void itemClickedmethod(View view,int position) {
Bundle extras=new bundle();
and so. .the intent stuff. or somewhere else. Please help.
Bitmap implements Parcelable, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Taken from the answer given here
EDIT 1
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
use that to get the bitmap attached to an ImageView. (image is the imageview)
try with this code this code is working :-
imageUrl = "nameofimagefile or path of image at server side"
new LoadImage().execute(imageUrl);
// then
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(getActivity());
//pDialog.setMessage("Loading Image ....");
//pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
args[0]).getContent());
System.out.println("======" + bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
imgCompLogo.setImageBitmap(image);
//pDialog.dismiss();
} else {
//pDialog.dismiss();
}
}
}
Situation :
I am working on Client-Server Communication.
When the users save the data (name of product, image, note), it should be transferred to the server side of the database.
But, I don't know how to code http Post request on the client side(Android).
MyWishlistsActivity.java
public class MyWishlistsActivity extends ListActivity {
SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
int[] to = new int[] { R.id.name };
custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
this.setListAdapter(custAdapter);
}
#Override
protected void onResume() {
super.onResume();
new GetContacts().execute((Object[]) null);
}
#SuppressWarnings("deprecation")
#Override
protected void onStop() {
Cursor cursor = custAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
custAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor> {
SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
return dbConnector.getAllWishlists();
}
#Override
protected void onPostExecute(Cursor result) {
custAdapter.changeCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
startActivity(addWishlists);
//Client-Server
Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
startActivity(addWishlists2);
//Client-Server End
return super.onOptionsItemSelected(item);
}
}
AddWishlists.java
public class AddEditWishlists extends Activity {
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_wishlist);
setUpViews();
}
private void setUpViews() {
inputname = (EditText) findViewById(R.id.inputname);
inputnote = (EditText) findViewById(R.id.inputnote);
inputphoto = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
inputname.setText(extras.getString("name"));
inputnote.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputname.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
saveContactTask.execute((Object[]) null);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditWishlists.this);
alert.setTitle("Error In Save Wish List");
alert.setMessage("You need to Enter Name of the Product");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveContact() {
if(yourSelectedImage!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=image;}
SQLiteConnector sqlCon = new SQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
}
else {
sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
inputphoto.setImageBitmap(yourSelectedImage);
}
}
}
}
ViewWishlist.java
public class ViewWishlist extends Activity {
private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_wishlist);
setUpViews();
}
private void setUpViews() {
name = (TextView) findViewById(R.id.inputname);
note = (TextView) findViewById(R.id.inputnote);
photo = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
name.setText(extras.getString("name"));
note.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
backBtn=(Button)findViewById(R.id.back);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
CustomWishlistsAdapter.java
public class CustomWishlistsAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;
public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = inflator.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);
if (image != null) {
if (image.length > 3) {
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
final SQLiteConnector sqlCon = new SQLiteConnector(context);
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteWishlist(id);
Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
}
}
This is my code.
Please help me how to add http post request on this code..
And also the php on the Server side .
For the Android HttpPost (to send JSON serialized data to a server)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("url_of_the_server");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("note", note);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
//With response you can check the server return status code(to check if the request has been made correctly like so
StatusLine sLine = response.getStatusLine();
int statusCode = sLine.getStatusCode();
For more information on how to call a php web service there is a pretty nice tutorial that can be found here