I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need.
Here is my Adapter Class.
public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {
private static final String TAG = "resPoster";
private ArrayList<Poster> posterArrayList;
private Context context;
public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
this.posterArrayList = posterArrayList;
this.context = context;
}
#NonNull
#Override
public PosterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.sending_image_layout, viewGroup, false);
return new PosterViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull PosterViewHolder posterViewHolder, int i) {
posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/providers");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
Log.d(TAG,"filename: " + fileName);
File outFile = new File(dir, fileName);
Log.d(TAG,"outFile: " + outFile);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(i, 0);
((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
}
});
}
#Override
public int getItemCount() {
return posterArrayList.size();
}
public class PosterViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayoutImage;
ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
CircleImageView imageViewProfie;
public PosterViewHolder(#NonNull View posterView) {
super(posterView);
relativeLayoutImage = posterView.findViewById(R.id.image_relative);
imageViewBg = posterView.findViewById(R.id.image_bg);
imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
imageViewEdit = posterView.findViewById(R.id.edit_image);
imageViewDownload = posterView.findViewById(R.id.download_image);
imageViewShare = posterView.findViewById(R.id.share_image);
}
}
}
and I want to use this class
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
final Uri selectedUri = data.getData();
if (selectedUri != null) {
startCrop(selectedUri);
} else {
Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
Please Help me handle this method in interface.
Thank you.
**UPDATE: **
Here is my activity code to understand more my question.
RequestQueue requestQueue;
private ArrayList<Poster> posterArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private PosterAdapter posterAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sending_image);
requestQueue = Volley.newRequestQueue(this);
recyclerView = findViewById(R.id.recycler_poster);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
getAllPoster();
}
private void getAllPoster() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("poster_id", "1");
Log.d(TAG + "pp", String.valueOf(params));
String Url = Constants.Base_URL + "poster/";
JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
response -> {
Log.d("responsePending", String.valueOf(response));
try {
String statusResponseObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusResponseObject.equals("200")){
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pendingFragResponse = jsonArray.getJSONObject(i);
String posterObject = pendingFragResponse.getString("poster");
String positionObject = pendingFragResponse.getString("position");
String sizeObject = pendingFragResponse.getString("size");
String txt_positionObject = pendingFragResponse.getString("txt_position");
String titleObject = pendingFragResponse.getString("title");
String descriptionObject = pendingFragResponse.getString("description");
//
posterArrayList.add(new Poster(posterObject, positionObject,
sizeObject, txt_positionObject,
titleObject, descriptionObject));
posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
recyclerView.setAdapter(posterAdapter);
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
}
posterAdapter.notifyDataSetChanged();
// wp10ProgressBar.hideProgressBar();
}else {
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
Rather than using Interface pattern just create public method inside your adapter and call that method when your onActivityResult hits in Activity.
(This answer is just a workaround for your scenario. Ideally you should not pass your activity Context to your adapter, rather than use Interface pattern and receive callback inside your activity whenever any action took place (like clicking on edit button) inside your activity and pass relevant data while trigger callback from your adapter.)
You can refer AllNoteActivity and NoteAdapter for reference here
So what you need to do is put the current method onActivityResult() from PosterAdapter to the activity. Then make the methods startCrop(), handleCropResult() and handleCropError() public (I assume are in PosterAdapter).
In the onActivityResult() change the call of startCrop() to posterAdapter.startCrop(). Same for the other methods. And that should do it.
Create a method in adapter
In your adapter class
public void waterverYouWantMethod(){
}
And call that method from Activity when onActivityResult mehtod called.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// call that method here
adapter.wateverYouWantMethod();
}
}
Related
when i select first video then async task send coreect file name with correct progress value but when select video one by one then async task send ambigous filename. i.e. second video comes with first video filename and first video progressor count, third video comes with first or second video filename and first or second video progressor count and so on, why?
MainActivity.java
-------------------
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SELECT_VIDEO = 0x100;
private ArrayList<UploadModel> uploadModels;
private LinearLayoutManager mLinearLayoutManager;
private UploadAdapter uploadAdapter;
private Activity activity;
private List<String> mPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
uploadModels = new ArrayList<>();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true); // put adding from bottom
recyclerView.setLayoutManager(mLinearLayoutManager);
uploadAdapter = new UploadAdapter(uploadModels);
recyclerView.setAdapter(uploadAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityFromGallery();
}
});
}
private void startActivityFromGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("video/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_SELECT_VIDEO);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Select Picture"), REQUEST_CODE_SELECT_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
if (requestCode == REQUEST_CODE_SELECT_VIDEO && resultCode == RESULT_OK) {
mPath = new ArrayList<>();
Uri uri = data.getData();
mPath.add(getVideoPath(uri, MainActivity.this));
loadVideo();
}
}
private void loadVideo() {
Log.d(TAG, "loadImage: " + mPath.size());
if (mPath != null && mPath.size() > 0) {
UploadModel messageModel = new UploadModelurl, mPath.get(0), UploadModel.STATUS_UPLOAD);
uploadAdapter.updateMessage(messageModel);
}
}
public static String getVideoPath(final Uri uri, final Activity activity) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
UploadAdapter.java
-----------------------
public class UploadAdapter extends RecyclerView.Adapter<UploadAdapter.ViewHolder> {
private final List<UploadModel> mValues;
public UploadAdapter(List<UploadModel> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_upload, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
if(holder.mItem.getStatus() == UploadModel.STATUS_UPLOADING) {
holder.mProgressBar.setVisibility(View.VISIBLE);
File file = new File(holder.mItem.getLocalUrl());
holder.mIdView.setText(file.getName());
}
if(holder.mItem.getStatus() == UploadModel.STATUS_UPLOAD) {
holder.mItem.setStatus(UploadModel.STATUS_UPLOADING);
holder.mProgressBar.setVisibility(View.VISIBLE);
File file = new File(holder.mItem.getLocalUrl());
MessageUpload.convertVideo(holder.mItem, new MessageUpload.ProgressListener() {
#Override
public void onStart() {
holder.mIdView.setText(file.getName() + " Wait.........");
}
#Override
public void onFinish(boolean result) {
holder.mProgressBar.setVisibility(View.GONE);
holder.mIdView.setText(file.getName() + " finished ");
}
#Override
public void onProgress(float progress, String filename) {
holder.mIdView.setText(file.getName() + " " + progress + " %");
}
});
}else if(holder.mItem.getStatus() == UploadModel.STATUS_UPLOADED) {
holder.mIdView.setText(file.getName() + " finished ");
}
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
private final ProgressBar mProgressBar; // Resolve Issue #52
public UploadModel mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mProgressBar = (ProgressBar) view.findViewById(R.id.progress);
mIdView = (TextView) view.findViewById(R.id.textview);
}
}
public void updateMessage(UploadModel message) {
List<UploadModel> messageList = mValues;
int messagePosition = messageList.indexOf(message);
if (messagePosition >= 0 && messagePosition < messageList.size()) {
messageList.set(messagePosition, message);
} else {
messageList.add(message);
}
notifyDataSetChanged();
}
}
MessageUpload.java
-------------------------
public class MessageUpload {
public UploadMessage convertVideo(UploadModel messageModel, ProgressListener listener) {
UploadMessage task = new UploadMessage(listener);
task.execute(messageModel);
return task;
}
public interface ProgressListener {
void onStart();
void onFinish(boolean result);
void onProgress(float progress, String filename);
}
}
UploadMessage.java
-------------------------
public class UploadMessage extends AsyncTask<UploadModel, Integer, String> {
private final MessageUpload.ProgressListener mListener;
private UploadModel messageModel;
private String filename;
private long totalSize = 0;
public UploadMessage(MessageUpload.ProgressListener listener) {
this.mListener = listener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mListener.onStart();
}
#Override
protected void onProgressUpdate(Integer... progress) {
mListener.onProgress(progress[0], filename);
}
#Override
protected String doInBackground(UploadModel... params) {
messageModel = params[0];
File file = new File(messageModel.getLocalUrl());
filename = file.getName();
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(messageModel.getUrl());
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(messageModel.getLocalUrl());
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server responsetext
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mListener.onFinish(true);
}
}
//1.I am trying to pass Bar code value using ZXingScannerView scanner
//2. Then if scanned bar code is equals to JSON barcode object show item_name and cost from the JSON //file inside recyclerview, My issue is after scanning nothing is showing
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
scannerView = (ZXingScannerView) view.findViewById(R.id.zxscan);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(SecondFragment.this);
scannerView.startCamera();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getActivity(), "Please Accept The Permission", Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
})
.check();
return view;
}
#Override
public void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
if (Patterns.WEB_URL.matcher(rawResult.getText()).matches()) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(rawResult.getText()));
startActivity(browserIntent);
}
}
private void processRawResult(String text) {
if (text.startsWith("BEGIN:")){
String[] tokens = text.split("\n");
QRVCardModel qrvCardModel = new QRVCardModel();
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].startsWith("BEGIN:")) {
qrvCardModel.setType(tokens[i].substring("BEGIN:".length()));
}
else if (tokens[i].startsWith("N")) {
qrvCardModel.setName(tokens[i].substring("N:".length()));
}
else if (tokens[i].startsWith("ORG")) {
qrvCardModel.setOrg(tokens[i].substring("ORG:".length()));
}
else if (tokens[i].startsWith("TEL:")) {
qrvCardModel.setTel(tokens[i].substring("TEL:".length()));
}
else if (tokens[i].startsWith("URL:")) {
qrvCardModel.setUrl(tokens[i].substring("URL:".length()));
}
else if (tokens[i].startsWith("EMAIL:")) {
qrvCardModel.setEmail(tokens[i].substring("EMAIL:".length()));
}
else if (tokens[i].startsWith("ADS:")) {
qrvCardModel.setEmail(tokens[i].substring("ADS:".length()));
}
else if (tokens[i].startsWith("NOTE:")) {
qrvCardModel.setNote(tokens[i].substring("NOTE:".length()));
}
else if (tokens[i].startsWith("SUMMERY:")) {
qrvCardModel.setSummer(tokens[i].substring("SUMMERY:".length()));
}
else if (tokens[i].startsWith("DTSTART:")) {
qrvCardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
}
else if (tokens[i].startsWith("DTEND:")) {
qrvCardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
}
else if (text.startsWith("hhtp://")||
text.startsWith("hhtps://")||
text.startsWith("www."))
{
QRURLMode qrurlMode = new QRURLMode(text);
}
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel= new QRGeoModel();
String delims = "[ ,?q= ] +";
String tokens[]= text.split(delims);
for (int i=0; i< tokens.length;i++)
{
if (tokens[i].startsWith("geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
}
else
{
Toast.makeText(getActivity(),"QR CODE PASS", Toast.LENGTH_SHORT).show();
String json;
try {
InputStream is = getActivity().getAssets().open("products.json");
Toast.makeText(getActivity(), "JSON1", Toast.LENGTH_SHORT).show();
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//Toast.makeText(getActivity(),"JSON2", Toast.LENGTH_SHORT).show();
json = new String(buffer, "UTF-8");
Log.d("JSONTestLogs", "JSON Raw Text: " + json);
JSONObject object = new JSONObject(json);
JSONArray productsArray = object.getJSONArray("products");
Log.d("JSONTestLogs", "Fetching the Products array from JSON File. Size: " + productsArray.length());
for (int i = 0; i < productsArray.length(); i++) {
JSONObject item = productsArray.getJSONObject(i);
Log.d("JSONTestLogs", "Item: " + i + "\n" + item.toString());
if (text.equals(item.getString("bar_code"))) {
products_name.add(item.getString("item_name"));
cost.add(item.getString("cost"));
}
}
}
catch
(IOException e)
{
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace(); }
}
scannerView.resumeCameraPreview(SecondFragment.this);
// Toast.makeText(getActivity(),"JSON3", Toast.LENGTH_SHORT).show();
}
}
after you scanned the barcode. I think add the barcode to your list here;
products_name.add(item.getString("item_name"));
After add operation, you did not refresh the recyclerview data.
This code part working just one time.
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
you should call this part again or you need a function inside your adapter which is notify the data of recyclerview.
I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}
try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code
We are creating a chat application using openfire, smack. In that there is a chatscreen where users can send and receive messages and media files. For storing messages we are using Realm as local db. I want to show the progress of files during upload of files.
My Upload file code is :
public void firebasestorageMeth(final String msg, final String path, final String filetype, final String mykey, final String otheruserkey, final String username) {
StorageReference riversRef = STORAGE_REFERENCE.child(mykey).child("files").child(GetTimeStamp.timeStampDate());
final String timestampdate = GetTimeStamp.timeStampDate();
final String timestamptime = GetTimeStamp.timeStampTime();
final long id = GetTimeStamp.Id();
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "0", "",path);
ChatHelper.addChatMesgRealmMedia1(cmr, this, mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_STARTING).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Log.d(TAG, cmr.getChatref()+cmr.getMsgid()+cmr.getMsgstring()+"file path extension upload file" + path);
riversRef.putFile(Uri.fromFile(new File(path)))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
umpref.setUri(String.valueOf(id), path);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d(TAG, "file uploaded" + downloadUrl);
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "1", String.valueOf(downloadUrl),path);
ChatHelper.addChatMesgRealmMedia1(cmr, getApplicationContext(), mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_SUCCESS).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmediaurl", String.valueOf(downloadUrl)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_FAILED).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
exception.printStackTrace();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", progress + " ").putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
}
});
}
The chatadapter code is :
public class ChatAdapter1 extends RecyclerView.Adapter<ChatAdapter1.MyViewHolder> {
ArrayList<ChatMessageRealm> mList = new ArrayList<>();
private Context context;
private UserSession session;
public static final int SENDER = 0;
public static final int RECIPIENT = 1;
String TAG = "ChatAdapter1";
public ChatAdapter1(ArrayList<ChatMessageRealm> list, Context context) {
this.mList = list;
this.context = context;
session = new UserSession(context);
}
#Override
public int getItemViewType(int position) {
if (mList.get(position).getSenderjid().matches(session.getUserKey())) {
return SENDER;
} else {
return RECIPIENT;
}
}
#Override
public int getItemCount() {
return mList.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case SENDER:
View viewSender = inflater.inflate(R.layout.row_chats_sender, viewGroup, false);
viewHolder = new MyViewHolder(viewSender);
break;
case RECIPIENT:
View viewRecipient = inflater.inflate(R.layout.row_chats_receiver, viewGroup, false);
viewHolder = new MyViewHolder(viewRecipient);
break;
}
return (MyViewHolder) viewHolder;
}
#Override
public void onBindViewHolder(final ChatAdapter1.MyViewHolder holder, int position) {
final ChatMessageRealm comment = mList.get(position);
holder.setIsRecyclable(false);
// holder.otherSender_sender.setText(comment.getSenderjid());
holder.otherSender_Timestamp.setText(comment.getSendertime() + "," + comment.getSenderdate());
// holder.status.setVisibility(View.GONE);
switch (comment.getMsgtype()) {
case "text":
// holder.btndown.setVisibility(View.GONE);
String decryptedmsg = comment.getMsgstring();
holder.commentString.setText(decryptedmsg);
// holder.photo.setVisibility(View.GONE);
break;
case "photo":
Glide.clear(holder.imgchat);
holder.imgchat.setVisibility(View.VISIBLE);
holder.progress.setVisibility(View.VISIBLE);
if (getItemViewType(position) == SENDER) {
// holder.btndown.setVisibility(View.GONE);
// holder.btnopen.setVisibility(View.VISIBLE);
try {
Glide.with(context).load(comment.getMsglocalurl()).into(holder.imgchat);
}catch (Exception e){
e.printStackTrace();
}
}
break;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView otherSender_Timestamp, commentString,progress;
public ImageView imgchat;
public Button btndown, btnopen;
public MyViewHolder(View itemView) {
super(itemView);
otherSender_Timestamp = (TextView) itemView.findViewById(R.id.meSender_TimeStamp);
commentString = (TextView) itemView.findViewById(R.id.commentString);
progress = (TextView) itemView.findViewById(R.id.mediaprogress);
imgchat = (ImageView) itemView.findViewById(R.id.imgchat);
btndown = (Button) itemView.findViewById(R.id.btndown);
btnopen = (Button) itemView.findViewById(R.id.btnopen);
}
}
}
ChatActivity code is:
public class ChatActivity extends ToadoBaseActivity {
private EditText typeComment;
private ImageButton sendButton, attachment, takephoto;
Intent intent;
private RecyclerView recyclerView;
DatabaseReference dbChat;
private String otheruserkey;
LinearLayoutManager linearLayoutManager;
private MarshmallowPermissions marshmallowPermissions;
private ArrayList<String> mResults = new ArrayList<>();
private ActionMode actionMode;
UploadFileService uploadFileService;
boolean mServiceBound = false;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm aa");
private ChatAdapter1 mAdapter;
LinkedHashSet<ChatMessageRealm> uniqueStrings = new LinkedHashSet<ChatMessageRealm>();
private ArrayList<ChatMessageRealm> chatList = new ArrayList<>();
private ArrayList<String> chatListIds = new ArrayList<>();
String username, mykey;
private UserSession session;
String receiverToken = "nil";
boolean clicked;
LinearLayout layoutToAdd;
LinearLayout commentView;
private ChildEventListener dbChatlistener;
ImageButton photoattach, videoattach;
Uri videoUri;
public String dbTableKey;
EncryptUtils encryptUtils = new EncryptUtils();
private ImageButton imgdocattach;
private ImageButton locattach;
private LinearLayout spamView;
TextView tvTitle;
ImageView imgprof;
private ArrayList<String> imagesPathList;
private final int PICK_IMAGE_MULTIPLE = 199;
private ProgressBar progressBar;
UserMediaPrefs umprefs;
private Boolean mBounded;
private String TAG = "ChatActivity";
// AbstractXMPPConnection connection;
Realm mRealm;
Boolean chatexists;
private String otherusername;
private String profpic;
private MyXMPP2 myxinstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
session = new UserSession(this);
mykey = session.getUserKey();
// connection = MyXMPP2.getInstance(this,).getConn();
mRealm = Realm.getDefaultInstance();
checkChatRef(otheruserkey);
clicked = false;
layoutToAdd = (LinearLayout) findViewById(R.id.attachmentpopup);
marshmallowPermissions = new MarshmallowPermissions(this);
spamView = (LinearLayout) findViewById(R.id.spamView);
umprefs = new UserMediaPrefs(this);
//get these 2 things from notifications also
intent = getIntent();
otheruserkey = intent.getStringExtra("otheruserkey");
otherusername = intent.getStringExtra("otherusername");
profpic = intent.getStringExtra("profpic");
System.out.println("recevier token chat act oncreate" + otheruserkey);
imgprof = (ImageView) findViewById(R.id.icon_profile);
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setText(otherusername);
commentView = (LinearLayout) findViewById(R.id.commentView);
progressBar = (ProgressBar) findViewById(R.id.progress);
typeComment = (EditText) findViewById(R.id.typeComment);
sendButton = (ImageButton) findViewById(R.id.sendButton);
attachment = (ImageButton) findViewById(R.id.attachment);
takephoto = (ImageButton) findViewById(R.id.takephoto);
photoattach = (ImageButton) findViewById(R.id.photoattach);
imgdocattach = (ImageButton) findViewById(R.id.docattach);
videoattach = (ImageButton) findViewById(R.id.videoattach);
locattach = (ImageButton) findViewById(R.id.locationattach);
myxinstance = MyXMPP2.getInstance(ChatActivity.this, getString(R.string.server), mykey);
mAdapter = new ChatAdapter1(chatList, this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(mAdapter);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(mykey + " chat created " + otheruserkey);
ChatMessageRealm cm = null;
if (!typeComment.getText().toString().matches("")) {
cm = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, typeComment.getText().toString(), mykey, GetTimeStamp.timeStampTime(), GetTimeStamp.timeStampDate(), "text", String.valueOf(GetTimeStamp.Id()), "1");
}
if (cm != null)
myxinstance.sendMessage(cm);
loadData();
typeComment.setText("");
}
});
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (layoutToAdd.getVisibility() == View.VISIBLE)
layoutToAdd.setVisibility(View.GONE);
else
layoutToAdd.setVisibility(View.VISIBLE);
}
});
takephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (ActivityNotFoundException anfe) {
anfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
mykey = session.getUserKey();
username = session.getUsername();
loadData();
}
private void loadData() {
Sort sort[] = {Sort.ASCENDING};
String[] fieldNames = {"msgid"};
RealmResults<ChatMessageRealm> shows = mRealm.where(ChatMessageRealm.class).equalTo("chatref", mykey + otheruserkey).findAllSorted(fieldNames, sort);
if (shows.size() > 0) {
Log.d(TAG, shows.size() + "LOAD DATA CALLED " + shows.get(shows.size() - 1).getMsgstring());
for (ChatMessageRealm cm : shows) {
if (!chatList.contains(cm)) {
chatList.add(cm);
}
if (!chatListIds.contains(cm.getMsgid())) {
chatListIds.add(cm.getMsgid());
}
mAdapter.notifyDataSetChanged();
}
mAdapter.notifyDataSetChanged();
recyclerView.scrollToPosition(chatList.size() - 1);
}
}
private void checkChatRef(String otheruserkey) {
RealmQuery<ActiveChats> query = mRealm.where(ActiveChats.class);
query.equalTo("otherkey", otheruserkey);
RealmResults<ActiveChats> result1 = query.findAll();
if (result1.size() == 0) {
chatexists = false;
} else {
chatexists = true;
}
System.out.println(result1.size() + "chat exists chatactivity" + chatexists);
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(this.reloadData, new IntentFilter("reloadchataction"));
}
#Override
protected void onStop() {
super.onStop();
if (reloadData != null)
unregisterReceiver(reloadData);
}
private void dispatchTakePictureIntent() throws IOException {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "request code chatactivity" + requestCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
Log.d(TAG, "crop activity");
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
final String imguri = result.getUri().toString();
try {
final File file = createImageFile();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
InputStream in = null;
OutputStream out = null;
try {
in = getContentResolver().openInputStream(Uri.parse(imguri));
out = new FileOutputStream(file);
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
String s = file.getAbsolutePath();
Log.d(TAG, "image cropped uri chatact22" + file.getAbsolutePath());
Intent intent = new Intent(ChatActivity.this, ImageComment.class);
intent.putExtra("URI", s);
intent.putExtra("comment_type", "photo");
startImageComment(intent);
} catch (Exception ex) {
Log.e("Something went wrong.", ex.toString());
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "pic-" + GetTimeStamp.timeStamp() + ".jpg";
File image = OpenFile.createFile(this, imageFileName);
// Save a file: path for use with ACTION_VIEW intents
Log.d(TAG, "file createimagefile: " + image.getAbsolutePath());
return image;
}
private void startImageComment(Intent intent) {
Log.d(TAG, "image comment sending" + intent.getStringExtra("URI"));
intent.putExtra("username", username);
intent.putExtra("otheruserkey", otheruserkey);
intent.putExtra("receiverToken", receiverToken);
intent.putExtra("mykey", mykey);
startActivity(intent);
}
BroadcastReceiver reloadData = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra("reloadchat") != null) {
Log.d(TAG, " reloading data broadcast receiver" + intent.getStringExtra("reloadchat"));
loadData();
mAdapter.notifyDataSetChanged();
} else if (intent.getStringExtra("reloadchatmediastatus") != null) {
if (intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_STARTING))
loadData();
Log.d(TAG, " reloading data status " + intent.getStringExtra("reloadchatmediastatus"));
Log.d(TAG, " reloading data media id " + intent.getStringExtra("reloadchatmediaid"));
if (!intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_FAILED)) {
final String msgid = intent.getStringExtra("reloadchatmediaid");
String fileprogress = intent.getStringExtra("reloadchatmediastatus");
int ind1 = chatListIds.indexOf(msgid);
Log.d(TAG, ind1 + "chat list broadcast progress " + fileprogress);
Log.d(TAG, "chat list broadcast" + chatListIds.size());
try {
// View ve = linearLayoutManager.findViewByPosition(ind1);
// View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView;
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (intent.getStringExtra("reloadchatmediaurl") != null)
Log.d(TAG, " reloading data media url " + intent.getStringExtra("reloadchatmediaurl"));
}
};
}
I am trying to update my recyclerview dynamically in the broadcast receiver- reloadData in ChatActivity.
My logs tell me that i am receiving correct data from the sendbroadcast in the UploadFileService, the problem is in following code inside the broadcast receiver on ChatActivity, it is getting correct data but the data is not showing on the recycler view:
try {
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
I get correct values , such as:
08-03 19:31:25.240 705-705/com.app.toado D/ChatActivity: 0,30,file prog 34 VIEW HOLDER? android.widget.LinearLayout{ff24ae0 V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.346 705-705/com.app.toado D/ChatActivity: 0,30,file prog 100 VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.347 705-705/com.app.toado D/ChatActivity: 0,30,file prog upload success VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
I have tried using View ve = linearLayoutManager.findViewByPosition(ind1); and View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView; but they are also not working. Also tried adding notifydatasetchanged to it.
The try catch is also not throwing any error in the logs.
Can someone please help in figuring out why are the changes not showing on the recycler view but are showing in logs?
Are you sure you're updating the RecyclerView's Adapter from the UI Thread? Whenever you try to update the ViewHolder, you have to be certain you're doing so on the UI or it will not behave as expected.
When the modification to the ViewHolder is changed, check that Looper.myLooper().equals(Looper.getMainLooper());. If it returns false, it means you aren't updating on the UI Thread, the necessary place for all graphical updates to be made.
If this is the case, you just need to make sure that you can synchronize your changes on the UI, using Activity.runOnUiThread(Runnable r);.
How to set local video URI/Path/File to MediaInfo.Builder() of chromecast ? Also, anyone could please help me with a code snippet on how to load image and video locally from android storage and cast it to the google chrome cast ?
Read other questions too but over there it has been mentioned to create a local server on app. If really we need to do this then how to implement this ? I am using code available on https://github.com/googlecast/CastVideos-android but over there video is fetched and played from url. I want to load video from local storage also i want to show images also.
Updated:
Now I have a created a local server using "NanoHttpD" but is unable to get the url of selected local file. Below is my Acitivities code snippet:
public class VideoBrowserFragment extends Fragment implements VideoListAdapter.ItemClickListener,
LoaderManager.LoaderCallbacks<List<MediaInfo>> {
private static final String TAG = "zz VideoBrowserFragment";
private static final int REQUEST_TAKE_GALLERY_VIDEO = 123;
private static final String CATALOG_URL =
"http://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json";
private RecyclerView mRecyclerView;
private VideoListAdapter mAdapter;
private View mEmptyView;
private View mLoadingView;
private VideoCastManager mCastManager;
private VideoCastConsumerImpl mCastConsumer;
private View btnLocalVideo;
LocalServer server;
String chosenExt = "";
String localFileName = "";
String localFilePath = "";
String formatedIpAddress = "";
Uri selectedImageUri;
public VideoBrowserFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Toast.makeText(getActivity(), "VideoBrowserFragment onCreateView", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onCreateView");
return inflater.inflate(R.layout.video_browser_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toast.makeText(getActivity(), "VideoBrowserFragment onViewCreated", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onViewCreated");
mRecyclerView = (RecyclerView) getView().findViewById(R.id.list);
mEmptyView = getView().findViewById(R.id.empty_view);
mLoadingView = getView().findViewById(R.id.progress_indicator);
btnLocalVideo = getView().findViewById(R.id.btnLocalVideo);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new VideoListAdapter(this);
mRecyclerView.setAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
mCastManager = VideoCastManager.getInstance();
mCastConsumer = new VideoCastConsumerImpl() {
#Override
public void onConnected() {
super.onConnected();
mAdapter.notifyDataSetChanged();
}
#Override
public void onDisconnected() {
super.onDisconnected();
mAdapter.notifyDataSetChanged();
}
};
mCastManager.addVideoCastConsumer(mCastConsumer);
//fetch local video
btnLocalVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);
}
});
}
//get data of locally fetched videos....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
selectedImageUri = data.getData();
Toast.makeText(getActivity(), "Sending local video data", Toast.LENGTH_SHORT).show();
MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, "Local Subtitle");
movieMetadata.putString(MediaMetadata.KEY_TITLE, "Local Video is playing");
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject();
jsonObj.put("description", "Sample Descrioption over here");
} catch (JSONException e) {
Log.e(TAG, "Failed to add description to the json object", e);
}
String filePath = getPath(selectedImageUri);
chosenExt = filePath.substring(filePath.lastIndexOf(".") + 1);
startLocalServer();
String localUrl = formatedIpAddress + localFilePath;
Log.d(TAG, "MediaInfo urlLocal: " + localUrl);
MediaInfo item = new MediaInfo.Builder(localUrl)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType("video/mp4")
.setMetadata(movieMetadata)
.setStreamDuration(333 * 1000)
.build();
Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));
Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
intent.putExtra("media", Utils.mediaInfoToBundle(item));
intent.putExtra("shouldStart", false);
intent.putExtra("isLocal", true);
intent.putExtra("videoUri", selectedImageUri.toString());
/* Pair<View, String> imagePair = Pair
.create((View) viewHolder.getImageView(), transitionName);*/
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(getActivity());
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
}
}
}
//get path of video fetched...
public String getPath(Uri uri) {
Log.d(TAG, "uri is " + uri);
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), uri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
//int column_index1 = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
Uri filePathUri = Uri.parse(cursor.getString(column_index));
String file_name = filePathUri.getLastPathSegment().toString();
String file_path = filePathUri.getPath();
localFileName = file_name;
localFilePath = file_path;
Toast.makeText(getActivity(), "File Name & PATH are:" + file_name + "\n" + file_path, Toast.LENGTH_LONG).show();
Log.d("zz fileData: ", "fp: " + file_path + " :and: fn: " + file_name);
}
String result = cursor.getString(column_index);
cursor.close();
return result;
}
#Override
public void onDetach() {
Toast.makeText(getActivity(), "VideoBrowserFragment onDetach", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onDetach");
mCastManager.removeVideoCastConsumer(mCastConsumer);
super.onDetach();
}
#Override
public void itemClicked(View view, MediaInfo item, int position) {
Toast.makeText(getActivity(), "VideoBrowserFragment itemClicked", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment itemClicked");
if (view instanceof ImageButton) {
Log.d(TAG, "menu was clicked");
com.scriptlanes.cast2.utils.Utils.showQueuePopup(getActivity(), view, item);
} else {
String transitionName = getString(R.string.transition_image);
VideoListAdapter.ViewHolder viewHolder =
(VideoListAdapter.ViewHolder) mRecyclerView.findViewHolderForPosition(position);
Pair<View, String> imagePair = Pair
.create((View) viewHolder.getImageView(), transitionName);
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(getActivity(), imagePair);
Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
Log.d(TAG, "VideoBrowserFragment itemClicked media :" + Utils.mediaInfoToBundle(item));
intent.putExtra("media", Utils.mediaInfoToBundle(item));
intent.putExtra("shouldStart", false);
//isUrl=true, isLocal=false
intent.putExtra("isLocal", false);
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
}
}
#Override
public Loader<List<MediaInfo>> onCreateLoader(int id, Bundle args) {
Toast.makeText(getActivity(), "VideoBrowserFragment onCreateLoader", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onCreateLoader");
return new VideoItemLoader(getActivity(), CATALOG_URL);
}
#Override
public void onLoadFinished(Loader<List<MediaInfo>> loader, List<MediaInfo> data) {
Toast.makeText(getActivity(), "VideoBrowserFragment onLoadFinished", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onLoadFinished");
mAdapter.setData(data);
mLoadingView.setVisibility(View.GONE);
mEmptyView.setVisibility(null == data || data.isEmpty() ? View.VISIBLE : View.GONE);
}
#Override
public void onLoaderReset(Loader<List<MediaInfo>> loader) {
Toast.makeText(getActivity(), "VideoBrowserFragment onLoaderReset", Toast.LENGTH_SHORT).show();
Log.d(TAG, "VideoBrowserFragment onLoaderReset");
mAdapter.setData(null);
}
/*temp code nanohttpd*/
public class LocalServer extends NanoHTTPD {
private final Logger LOG = Logger.getLogger(LocalServer.class.getName());
public void main(String[] args) {
ServerRunner.run(LocalServer.class);
}
public LocalServer() {
super(3000);
Log.d("zz nanaHttpd: ", "STARTED");
}
#Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) {
//String mediasend = getExtension(chosenFile);
Log.d("zz nanaHttpd: ", "uri: " + uri+" , method: "+method);
FileInputStream fis = null;
File file = new File(localFilePath);
Log.e("Creando imputStream", "Size: ");
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fis);
}
}
private void startLocalServer() {
server = new LocalServer();
try {
server.start();
} catch (IOException ioe) {
Log.d("zz Httpd", "The server could not start.");
}
Log.d("zz Httpd", "Web server initialized.");
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
Log.d("zz Httpd IP U: ", ipAddress + "");
String formatedIpAddress1 = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
formatedIpAddress = "http://" + formatedIpAddress1 + ":" + server.getListeningPort();
Log.d("zz Httpd IP: ", "Please access! " + formatedIpAddress);
}
#Override
public void onDestroy() {
super.onDestroy();
//server.stop();
}
}
As you have seen in other posts, you need to add an embedded web server to your app and expose your local content in that web server. Then you need to send the url of these local contents to your chromecast. There are a number of open source small embedded http servers that can be used if you don't want to build write your own tiny http server, you can google for such embedded solutions.
Your are doing it right, Just put the selected url like this:
mediaMetadata.addImage(new WebImage(Uri.parse(http://192.168.0.XX:8080/video.mp4));