This is my full code below. am coding an android app that can select image from gallery or any where and upload it to Mysql server through php but if image is not selected and the upload button is press the application crashes so i want to implement the function that it shows error dialog / warning dialog if image is not selected from gallery have already implemented it in EditText but cannot implement it in Image. below is my code
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Just copy this code and paste
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Related
When i Try to build then this error will come. Actually i have integrated another app source code in my existing app source code. Error: class ActivitySigUupBinding is public, should be declared in a file named ActivitySignUpBinding.java public final class ActivitySigUupBinding implements ViewBinding
ActivitySignUpBinding.java ⬇️
public final class ActivitySignUpBinding implements ViewBinding {
#NonNull
private final ConstraintLayout rootView;
#NonNull
public final EditText editText;
#NonNull
public final ImageView imageView;
#NonNull
public final EditText password;
#NonNull
public final ProgressBar pb;
#NonNull
public final TextView privacy;
#NonNull
public final Button signUp;
#NonNull
public final TextView terms;
#NonNull
public final TextView textView;
#NonNull
public final TextView textView2;
#NonNull
public final EditText username;
private ActivitySignUpBinding(#NonNull ConstraintLayout rootView, #NonNull EditText
editText,
#NonNull ImageView imageView, #NonNull EditText password, #NonNull ProgressBar pb,
#NonNull TextView privacy, #NonNull Button signUp, #NonNull TextView terms,
#NonNull TextView textView, #NonNull TextView textView2, #NonNull EditText username) {
this.rootView = rootView;
this.editText = editText;
this.imageView = imageView;
this.password = password;
this.pb = pb;
this.privacy = privacy;
this.signUp = signUp;
this.terms = terms;
this.textView = textView;
this.textView2 = textView2;
this.username = username;
}
#Override
#NonNull
public ConstraintLayout getRoot() {
return rootView;
}
#NonNull
public static ActivitySignUpBinding inflate(#NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
#NonNull
public static ActivitySignUpBinding inflate(#NonNull LayoutInflater inflater,
#Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_sign_up, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
#NonNull
public static ActivitySignUpBinding bind(#NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.editText;
EditText editText = rootView.findViewById(id);
if (editText == null) {
break missingId;
}
id = R.id.imageView;
ImageView imageView = rootView.findViewById(id);
if (imageView == null) {
break missingId;
}
id = R.id.password;
EditText password = rootView.findViewById(id);
if (password == null) {
break missingId;
}
id = R.id.pb;
ProgressBar pb = rootView.findViewById(id);
if (pb == null) {
break missingId;
}
id = R.id.privacy;
TextView privacy = rootView.findViewById(id);
if (privacy == null) {
break missingId;
}
id = R.id.signUp;
Button signUp = rootView.findViewById(id);
if (signUp == null) {
break missingId;
}
id = R.id.terms;
TextView terms = rootView.findViewById(id);
if (terms == null) {
break missingId;
}
id = R.id.textView;
TextView textView = rootView.findViewById(id);
if (textView == null) {
break missingId;
}
id = R.id.textView2;
TextView textView2 = rootView.findViewById(id);
if (textView2 == null) {
break missingId;
}
id = R.id.username;
EditText username = rootView.findViewById(id);
if (username == null) {
break missingId;
}
return new ActivitySignUpBinding((ConstraintLayout) rootView, editText, imageView,
password,
pb, privacy, signUp, terms, textView, textView2, username);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
FrontSignup.java ⬇️
public class FrontSignup extends AppCompatActivity {
ActivitySignupBinding binding;
Activity activity;
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
AlertDialog loadingDialog,alert;
Session session;
boolean check=false;
boolean email_=false;
boolean emailactive= false;
private static final int SELECT_PICTURE = 0;
private Bitmap bitmap;
String filepath,encodedimage;
int type;
Uri image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
binding=ActivitySignupBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
activity=FrontSignup.this;
session= new Session(activity);
loadingDialog=Method.loading(activity);
alert=Method.Alerts(activity);
if(Constant.EMAIL_VERIFICATION){
type=2;
}else {
type=5;
}
binding.layoutImg.setOnClickListener(v -> Dexter.withActivity(FrontSignup
.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {}
#Override
public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check());
binding.sendAgain.setOnClickListener(v -> {
funVerifyEmail(binding.email.getText().toString().trim());
});
binding.terms.setOnClickListener(v -> {
Method.launchCustomTabs(activity, Constant.PRIVACY_POLICY_URL);
});
}
void showLoading(){
loadingDialog.show();
}
void dismisLoading(){
if(loadingDialog.isShowing())
loadingDialog.dismiss();
}
private boolean validateData() {
boolean valid= true;
if(TextUtils.isEmpty(binding.username.getText().toString().trim())){
binding.username.setError(getResources().getString(R.string.error_field_required));
valid=false;
}
if(TextUtils.isEmpty(binding.email.getText().toString().trim())){
binding.email.setError(getResources().getString(R.string.error_field_required));
valid=false;
}
else if(!binding.email.getText().toString().trim().matches(emailPattern)){
binding.email.setError(getResources().getString(R.string.error_invalid_email));
valid=false;
}
if(TextUtils.isEmpty(binding.password.getText().toString().trim())){
binding.password.setError(getResources().getString(R.string.error_invalid_password));
valid=false;
}
if(image==null){
showAlert(getString(R.string.please_select_profile_image));
valid=false;
}
return valid;
}
public void Signup(View view) {
if(!Method.isConnected(activity)){
Method.ToastWarning(activity,getString(R.string.no_internet));
}
if(!validateData()){
return;
}else {
if(check){
if(email_){
funOtpVerify(binding.email.getText().toString().trim(),binding.otp.getText().toString().trim());
}else{
reqSignup(binding.username.getText().toString().trim(),binding.email.getText().toString().trim(),binding.password.getText().toString().trim(),5);
}
}else {
reqSignup(binding.username.getText().toString().trim(),binding.email.getText().toString().trim(),binding.password.getText().toString().trim(),type);
}
}
}
private void reqSignup(String name, String email, String password, int types) {
File file = new File(filepath);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData("newimage", file.getName(), requestBody);
OSDeviceState device = OneSignal.getDeviceState();
Constant.API_TYPE = "signup";
Constant.P1 = name;
Constant.P2 = email;
Constant.P3 = password;
Constant.P4 = Method.deviceId(activity);
Constant.P5 = device.getUserId();
Constant.P6 = String.valueOf(types);
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).Signup(parts);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if(response.isSuccessful() && response.body().getStatus()==201){
check=true;
if(types==5){
session.saveUserData("",email,"","",password,"","","","");
session.setBoolean(session.LOGIN,true);
Method.ToastSuccess(activity,"Account Created!");
Intent intent = new Intent(activity, FrontLogin.class);
overridePendingTransition(R.anim.enter,R.anim.exit);
startActivity(intent);
}else{
binding.loginLayout.setVisibility(View.GONE);
binding.layoutOtp.setVisibility(View.VISIBLE);
funVerifyEmail(email);
}
}else{
Method.ToastError(activity,response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
}
});
}
public void login(View view) {
overridePendingTransition(R.anim.exit,R.anim.enter);
startActivity(new Intent(activity,FrontLogin.class));
}
private void funOtpVerify(String email , String otp) {
if(otp.isEmpty()){
Method.ToastWarning(activity,"Enter Valid Otp");
}else {
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).Verify_OTP(otp, email);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if (response.isSuccessful() && response.body().getStatus() == 201) {
reqSignup(binding.username.getText().toString().trim(), binding.email.getText().toString().trim(), binding.password.getText().toString().trim(), 5);
} else {
binding.otp.setText(null);
Method.ToastError(activity, response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
}
});
}
}
private void funVerifyEmail(String email) {
emailactive=true;
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).VerifyEmail(email);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if(response.isSuccessful() && response.body().getStatus()==201) {
email_=true;
Method.ToastSuccess(activity,"OTP has been sended To Email");
binding.procced.setText(getString(R.string.verify_otp));
} else {
Method.ToastWarning(activity,response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
Method.ToastWarning(activity,getString(R.string.try_again_later));
}
});
}
public String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && data != null) {
image = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(image);
bitmap = BitmapFactory.decodeStream(inputStream);
Bitmap.createScaledBitmap(bitmap, 120, 120, false);
binding.image.setImageBitmap(bitmap);
filepath=getRealPathFromURI(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
void showAlert(String msg){
alert.show();
TextView tv =alert.findViewById(R.id.txt);
tv.setText(msg);
alert.findViewById(R.id.close).setOnClickListener(v -> {
alert.dismiss();
});
}
#Override
public void onBackPressed() {
if(emailactive){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.txt_exit));
builder.setMessage(getString(R.string.txt_confirm_exit));
builder.setPositiveButton(getString(R.string.txt_yes), (dialog, which) -> {
overridePendingTransition(R.anim.exit,R.anim.enter);
finish();
});
builder.setNegativeButton(getString(R.string.txt_no), (dialog, which) -> {
dialog.dismiss();
});
AlertDialog alert = builder.create();
alert.show();
}
super.onBackPressed();
}
}
Error ⬇️
// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference
I have successfully uploaded the media in the firebase but i'm unable to retrieve it. apparently it shows that the media_problem is pointing to a null object. below is my code.
This is my code to retrieve:
this.view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "TOO FAST! TRY AGAIN", Toast.LENGTH_LONG);
try {
Dash_agri.this.firestore.collection("problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete( Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
Dash_agri.this.records.clear();
Iterator it = ((QuerySnapshot) task.getResult()).iterator();
while (it.hasNext()) {
QueryDocumentSnapshot document = (QueryDocumentSnapshot) it.next();
Dash_agri.this.single_ID = document.getId();
Dash_agri.this.single_name = (String) document.get("NAME_problems");
Dash_agri.this.single_phone = (String) document.get("PHONE_problems");
Dash_agri.this.single_description = (String) document.get("DESCRIPTION_problems");
Dash_agri.this.single_URL = (String) document.get("MEDIA_problems");
String view_media = "Touch to view media";
new SpannableString(view_media).setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
}, 0, 9, 33);
Dash_agri.this.record_id.add(Dash_agri.this.single_ID);
ArrayList<String> arrayList = Dash_agri.this.records;
StringBuilder sb = new StringBuilder();
sb.append("QUERY#");
sb.append(Dash_agri.this.single_ID);
sb.append(" by ");
sb.append(Dash_agri.this.single_name);
sb.append("\n");
sb.append(Dash_agri.this.single_description);
sb.append("\n\n");
sb.append(view_media);
arrayList.add(sb.toString());
}
}
}
});
} catch (Exception e) {
Toast.makeText(Dash_agri.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
Dash_agri.this.listView.setAdapter(new ArrayAdapter<>(Dash_agri.this.getApplicationContext(), R.layout.simple_list_item_1, Dash_agri.this.records));
}
});
This is my code to upload:
public class Upload extends AppCompatActivity {
private static final int PICK_MEDIA_REQUEST = 1;
String MEDIA_url;
String NAME;
String PHONE;
long TIME_ID = System.currentTimeMillis();
String USER_ID;
TextView file;
FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
Button img;
EditText prob;
ProgressBar progressBar;
StorageReference storageReference;
Button upld;
/* access modifiers changed from: private */
public Uri uri;
Button vid;
/* access modifiers changed from: protected */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1 && data != null && data.getData() != null) {
this.uri = data.getData();
this.file.setText(this.uri.getPath());
}
}
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_upload);
this.firebaseAuth = FirebaseAuth.getInstance();
this.firestore = FirebaseFirestore.getInstance();
this.storageReference = FirebaseStorage.getInstance().getReference();
this.prob = (EditText) findViewById(R.id.editTextProblem_upload);
this.file = (TextView) findViewById(R.id.textViewFile_upload);
this.img = (Button) findViewById(R.id.buttonImage_upload);
this.vid = (Button) findViewById(R.id.buttonVideo_Upload);
this.upld = (Button) findViewById(R.id.buttonUpload_upload);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar_upload);
this.progressBar.setVisibility(View.VISIBLE);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
Upload.this.startActivityForResult(intent, 1);
}
});
this.vid.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(intent, 1);
}
});
try {
this.upld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (prob.getText().toString().isEmpty() || file.getText().toString().equals("No file selected")) {
Toast.makeText(getApplicationContext(), "Please write your problem and upload a file!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
upload_file_also(uri);
USER_ID = firebaseAuth.getCurrentUser().getUid();
TIME_ID = System.currentTimeMillis();
firestore.collection("users").document(USER_ID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
NAME = documentSnapshot.getString("NAME_");
PHONE = documentSnapshot.getString("PHONE_");
}
});
NAME = NAME == null ? "null" : NAME;
PHONE = PHONE == null ? "null" : PHONE;
if (!NAME.equals("null") && !PHONE.equals("null")) {
CollectionReference collection = firestore.collection("problems");
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(TIME_ID);
DocumentReference documentReference = collection.document(String.valueOf(sb.toString()));
Map<String, Object> user_problems = new HashMap<>();
user_problems.put("DESCRIPTION_problems", prob.getText().toString());
user_problems.put("NAME_problems", NAME);
user_problems.put("PHONE_problems", PHONE);
user_problems.put("MEDIA_problems", Upload.this.MEDIA_url);
documentReference.set(user_problems).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
Toast.makeText(Upload.this.getApplicationContext(), "Successfully uploaded", Toast.LENGTH_SHORT).show();
Upload.this.startActivity(new Intent(Upload.this.getApplicationContext(), Dash_farmer.class));
Upload.this.finish();
}
});
}
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* access modifiers changed from: private */
public void upload_file_also(Uri fileUri) {
StorageReference storageReference2 = this.storageReference;
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(this.TIME_ID);
final StorageReference sr = storageReference2.child(String.valueOf(sb.toString()));
sr.putFile(fileUri).addOnSuccessListener((OnSuccessListener<TaskSnapshot>) new OnSuccessListener<TaskSnapshot>() {
public void onSuccess(TaskSnapshot taskSnapshot) {
sr.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
Upload.this.MEDIA_url = uri.toString();
Upload.this.progressBar.setVisibility(View.VISIBLE);
Upload.this.upld.setText("TAP AGAIN TO UPLOAD MEDIA");
}
});
}
});
}
}
I'm unable to find why this isn't working. Please put a light on where this is going wrong.
So I have an app which plays media in ExoPlayer2 but now I wanted to add a button which can open the same video in an external player.
I am actually not getting what to add in intent so help is required.
Here's the open in external button option I'm trying to add:
imgPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
}
});
Now the issue is, idk what to add in Uri.parse(), I want the currently playing video to be played in an external player.
Thanks in advance.
Edit:
My Activity Class:
public class DetailsActivity extends AppCompatActivity {
int i = 0;
private TextView tvName,tvDirector,tvRelease,tvCast,tvDes,tvGenre,tvRelated;
private RecyclerView rvDirector,rvServer,rvRelated,rvComment;
public static RelativeLayout lPlay;
private EpisodeAdapter episodeAdapter;
private HomePageAdapter relatedAdapter;
private LiveTvHomeAdapter relatedTvAdapter;
public static LinearLayout llBottom,llBottomParent,llcomment;
private SwipeRefreshLayout swipeRefreshLayout;
private String type="",id="";
private ImageView imgAddFav;
public static ImageView imgBack;
public static ImageView imgPlayer;
private String V_URL = "";
public static WebView webView;
public static ProgressBar progressBar;
private boolean isFav = false;
private ShimmerFrameLayout shimmerFrameLayout;
private Button btnComment;
private EditText etComment;
private CommentsAdapter commentsAdapter;
private String commentURl;
private AdView adView;
private InterstitialAd mInterstitialAd;
public static SimpleExoPlayer player;
public static PlayerView simpleExoPlayerView;
public static SubtitleView subtitleView;
public static ImageView imgFull;
public static ImageView imgfit;
public static boolean isPlaying,isFullScr;
public static View playerLayout;
private int playerHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
llBottom=findViewById(R.id.llbottom);
swipeRefreshLayout=findViewById(R.id.swipe_layout);
imgAddFav=findViewById(R.id.add_fav);
imgBack=findViewById(R.id.img_back);
webView=findViewById(R.id.webView);
progressBar=findViewById(R.id.progressBar);
llBottomParent=findViewById(R.id.llbottomparent);
lPlay=findViewById(R.id.play);
rvRelated=findViewById(R.id.rv_related);
tvRelated=findViewById(R.id.tv_related);
shimmerFrameLayout=findViewById(R.id.shimmer_view_container);
simpleExoPlayerView = findViewById(R.id.video_view);
subtitleView=findViewById(R.id.subtitle);
playerLayout=findViewById(R.id.player_layout);
imgFull=findViewById(R.id.img_full_scr);
imgfit=findViewById(R.id.fit);
rvServer=findViewById(R.id.rv_server_list);
imgPlayer=findViewById(R.id.img_player);
shimmerFrameLayout.startShimmer();
playerHeight = lPlay.getLayoutParams().height;
progressBar.setMax(100); // 100 maximum value for the progress value
progressBar.setProgress(50);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
imgBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
imgPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
}
});
type = getIntent().getStringExtra("vType");
id = getIntent().getStringExtra("id");
final SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
if (preferences.getBoolean("status",false)){
imgAddFav.setVisibility(VISIBLE);
}else {
imgAddFav.setVisibility(GONE);
}
imgFull.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFullScr){
isFullScr=false;
showSystemUI();
llBottomParent.setVisibility(VISIBLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
lPlay.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, playerHeight));
imgfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
}
});
}else {
hideSystemUI();
isFullScr=true;
llBottomParent.setVisibility(GONE);
lPlay.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imgfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
Runnable r = new Runnable() {
#Override
public void run() {
i = 0;
}
};
if (i == 1) {
//Single click
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
} else if (i == 2) {
//Double click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
} else if (i == 3) {
// Triple Click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
} else if (i == 4) {
// Fourth Click
i = 0;
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
}
}
});
}
}
});
imgAddFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = new ApiResources().getAddFav()+"&&user_id="+preferences.getString("id","0")+"&&videos_id="+id;
if (isFav){
String removeURL = new ApiResources().getRemoveFav()+"&&user_id="+preferences.getString("id","0")+"&&videos_id="+id;
removeFromFav(removeURL);
}else {
addToFav(url);
}
}
});
if (!isNetworkAvailable()){
new ToastMsg(DetailsActivity.this).toastIconError(getString(R.string.no_internet));
}
initGetData();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initGetData();
}
});
}
private void initGetData(){
if (!type.equals("tv")){
//----related rv----------
relatedAdapter=new HomePageAdapter(this,listRelated);
rvRelated.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvRelated.setHasFixedSize(true);
rvRelated.setAdapter(relatedAdapter);
if (type.equals("tvseries")){
rvRelated.removeAllViews();
listRelated.clear();
rvServer.removeAllViews();
listDirector.clear();
listEpisode.clear();
episodeAdapter=new EpisodeAdapter(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(episodeAdapter);
getSeriesData(type,id);
}else {
rvServer.removeAllViews();
listDirector.clear();
rvRelated.removeAllViews();
listRelated.clear();
serverApater=new ServerApater(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(serverApater);
getData(type,id);
final ServerApater.OriginalViewHolder[] viewHolder = {null};
serverApater.setOnItemClickListener(new ServerApater.OnItemClickListener() {
#Override
public void onItemClick(View view, CommonModels obj, int position, ServerApater.OriginalViewHolder holder) {
iniMoviePlayer(obj.getStremURL(),obj.getServerType(),DetailsActivity.this);
serverApater.chanColor(viewHolder[0],position);
holder.name.setTextColor(getResources().getColor(R.color.colorPrimary));
viewHolder[0] =holder;
}
});
}
SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
String url = new ApiResources().getFavStatusURl()+"&&user_id="+sharedPreferences.getString("id","0")+"&&videos_id="+id;
if (sharedPreferences.getBoolean("status",false)){
getFavStatus(url);
}
}else {
llcomment.setVisibility(GONE);
tvRelated.setText("All TV :");
rvServer.removeAllViews();
listDirector.clear();
rvRelated.removeAllViews();
listRelated.clear();
//----related rv----------
relatedTvAdapter=new LiveTvHomeAdapter(this,listRelated);
rvRelated.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvRelated.setHasFixedSize(true);
rvRelated.setAdapter(relatedTvAdapter);
imgAddFav.setVisibility(GONE);
serverApater=new ServerApater(this,listDirector);
rvServer.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
rvServer.setHasFixedSize(true);
rvServer.setAdapter(serverApater);
getTvData(type,id);
llBottom.setVisibility(GONE);
final ServerApater.OriginalViewHolder[] viewHolder = {null};
serverApater.setOnItemClickListener(new ServerApater.OnItemClickListener() {
#Override
public void onItemClick(View view, CommonModels obj, int position, ServerApater.OriginalViewHolder holder) {
iniMoviePlayer(obj.getStremURL(),obj.getServerType(),DetailsActivity.this);
serverApater.chanColor(viewHolder[0],position);
holder.name.setTextColor(getResources().getColor(R.color.colorPrimary));
viewHolder[0] =holder;
}
});
}
}
private void initWeb(String s){
if (isPlaying){
player.release();
}
progressBar.setVisibility(GONE);
webView.loadUrl(s);
webView.setVisibility(VISIBLE);
playerLayout.setVisibility(GONE);
}
public void iniMoviePlayer(String url,String type,Context context){
Log.e("vTYpe :: ",type);
if (type.equals("embed") || type.equals("vimeo") || type.equals("gdrive")){
initWeb(url);
}else {
initVideoPlayer(url,context,type);
}
}
public void initVideoPlayer(String url,Context context,String type){
progressBar.setVisibility(VISIBLE);
if (player!=null){
player.release();
}
webView.setVisibility(GONE);
playerLayout.setVisibility(VISIBLE);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new
AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new
DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
player.setPlayWhenReady(true);
simpleExoPlayerView.setPlayer(player);
simpleExoPlayerView.setControllerVisibilityListener(new PlayerControlView.VisibilityListener() {
#Override
public void onVisibilityChange(int visibility) {
Log.e("Visibil", String.valueOf(visibility));
if (visibility==0){
imgBack.setVisibility(VISIBLE);
imgFull.setVisibility(VISIBLE);
imgfit.setVisibility(VISIBLE);
}else {
imgBack.setVisibility(GONE);
imgFull.setVisibility(GONE);
imgfit.setVisibility(GONE);
}
}
});
Uri uri = Uri.parse(url);
MediaSource mediaSource = null;
if (type.equals("hls")){
mediaSource = hlsMediaSource(uri,context);
}else if (type.equals("youtube")){
Log.e("youtube url :: ",url);
extractYoutubeUrl(url,context);
}
else if (type.equals("rtmp")){
mediaSource=rtmpMediaSource(uri);
}else {
mediaSource=mediaSource(uri);
}
player.prepare(mediaSource, true, false);
player.addListener(new Player.DefaultEventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playWhenReady && playbackState == Player.STATE_READY) {
isPlaying=true;
progressBar.setVisibility(View.GONE);
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
else if (playbackState==Player.STATE_READY){
progressBar.setVisibility(View.GONE);
isPlaying=false;
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
else if (playbackState==Player.STATE_BUFFERING) {
isPlaying=false;
progressBar.setVisibility(VISIBLE);
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
} else {
// player paused in any state
isPlaying=false;
Log.e("STATE PLAYER:::", String.valueOf(isPlaying));
}
}
});
}
private void extractYoutubeUrl(String url,Context context) {
new YouTubeExtractor(context) {
#Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
if (ytFiles != null) {
int itag = 18;
String downloadUrl = ytFiles.get(itag).getUrl();
Log.e("YOUTUBE::", String.valueOf(downloadUrl));
try {
MediaSource mediaSource = mediaSource(Uri.parse(downloadUrl));
player.prepare(mediaSource, true, false);
}catch (Exception e){
}
}
}
}.extract(url, true, true);
}
private MediaSource rtmpMediaSource(Uri uri){
MediaSource videoSource = null;
RtmpDataSourceFactory dataSourceFactory = new RtmpDataSourceFactory();
videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
return videoSource;
}
private MediaSource hlsMediaSource(Uri uri,Context context){
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/JioTV/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"), bandwidthMeter);
MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
return videoSource;
}
private MediaSource mediaSource(Uri uri){
return new ExtractorMediaSource.Factory(
new DefaultHttpDataSourceFactory("exoplayer")).
createMediaSource(uri);
}
private void addToFav(String url){
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("success")){
new ToastMsg(DetailsActivity.this).toastIconSuccess(response.getString("message"));
isFav=true;
imgAddFav.setBackgroundResource(R.drawable.outline_favorite_24);
}else {
new ToastMsg(DetailsActivity.this).toastIconError(response.getString("message"));
}
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
new ToastMsg(DetailsActivity.this).toastIconError(getString(R.string.error_toast));
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getTvData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
swipeRefreshLayout.setRefreshing(false);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
try {
tvName.setText(response.getString("tv_name"));
tvDes.setText(response.getString("description"));
V_URL=response.getString("stream_url");
CommonModels model=new CommonModels();
model.setTitle("HD");
model.setStremURL(V_URL);
model.setServerType(response.getString("stream_from"));
listDirector.add(model);
JSONArray jsonArray = response.getJSONArray("all_tv_channel");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
CommonModels models =new CommonModels();
models.setImageUrl(jsonObject.getString("poster_url"));
models.setTitle(jsonObject.getString("tv_name"));
models.setVideoType("tv");
models.setId(jsonObject.getString("live_tv_id"));
listRelated.add(models);
}
relatedTvAdapter.notifyDataSetChanged();
JSONArray serverArray = response.getJSONArray("additional_media_source");
for (int i = 0;i<serverArray.length();i++){
JSONObject jsonObject=serverArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("label"));
models.setStremURL(jsonObject.getString("url"));
models.setServerType(jsonObject.getString("source"));
listDirector.add(models);
}
serverApater.notifyDataSetChanged();
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getSeriesData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
swipeRefreshLayout.setRefreshing(false);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
try {
tvName.setText(response.getString("title"));
tvRelease.setText("Release On "+response.getString("release"));
tvDes.setText(response.getString("description"));
//----realted post---------------
JSONArray relatedArray = response.getJSONArray("related_tvseries");
for (int i = 0;i<relatedArray.length();i++){
JSONObject jsonObject=relatedArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("title"));
models.setImageUrl(jsonObject.getString("thumbnail_url"));
models.setId(jsonObject.getString("videos_id"));
models.setVideoType("tvseries");
listRelated.add(models);
}
relatedAdapter.notifyDataSetChanged();
//----episode------------
JSONArray mainArray = response.getJSONArray("season");
for (int i = 0;i<mainArray.length();i++){
//epList.clear();
JSONObject jsonObject=mainArray.getJSONObject(i);
CommonModels models=new CommonModels();
String season_name=jsonObject.getString("seasons_name");
models.setTitle(jsonObject.getString("seasons_name"));
Log.e("Season Name 1::",jsonObject.getString("seasons_name"));
JSONArray episodeArray=jsonObject.getJSONArray("episodes");
List<EpiModel> epList=new ArrayList<>();
for (int j=0;j<episodeArray.length();j++){
JSONObject object =episodeArray.getJSONObject(j);
EpiModel model=new EpiModel();
model.setSeson(season_name);
model.setEpi(object.getString("episodes_name"));
model.setStreamURL(object.getString("file_url"));
model.setServerType(object.getString("file_type"));
epList.add(model);
}
models.setListEpi(epList);
listDirector.add(models);
episodeAdapter=new EpisodeAdapter(DetailsActivity.this,listDirector);
rvServer.setAdapter(episodeAdapter);
episodeAdapter.notifyDataSetChanged();
}
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
private void getData(String vtype,String vId){
String type = "&&type="+vtype;
String id = "&id="+vId;
String url = new ApiResources().getDetails()+type+id;
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(GONE);
swipeRefreshLayout.setRefreshing(false);
try {
tvName.setText(response.getString("title"));
tvRelease.setText("Released On "+response.getString("release"));
tvDes.setText(response.getString("description"));
//----realted post---------------
JSONArray relatedArray = response.getJSONArray("related_movie");
for (int i = 0;i<relatedArray.length();i++){
JSONObject jsonObject=relatedArray.getJSONObject(i);
CommonModels models=new CommonModels();
models.setTitle(jsonObject.getString("title"));
models.setImageUrl(jsonObject.getString("thumbnail_url"));
models.setId(jsonObject.getString("videos_id"));
models.setVideoType("movie");
listRelated.add(models);
}
relatedAdapter.notifyDataSetChanged();
}catch (Exception e){
}finally {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
}
});
new VolleySingleton(DetailsActivity.this).addToRequestQueue(jsonObjectRequest);
}
}
Pass the url of your video, use it like this
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("http://Your URL"), "video/*");
startActivity(Intent.createChooser(intent, "Complete action using"));
For pausing your Exoplayer
exoplayer.playWhenReady(false);
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}