I want to create a custom exit dialog box with three images that images are fetching from server. Dialog is show if i click back button. Dialog is showed to me but images that are fetched from server are not shown, default images are showing. Image url is successfully getting from server. If i place that url in my imageView an exception is generated:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.madnanijaz.labassignment1, PID: 2967
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:22)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:383)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:181)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:170)
My code of Back Pressed button is:
#Override
public void onBackPressed() {
//Fetching Images(Adds from server)
fetchingAddsFromServer();
//CustomAlertDialog
final AlertDialog.Builder builder=new
AlertDialog.Builder(MainActivity.this);
View view=
LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setView(view);
builder.show();
// AlertDialog alertDialog=builder.create();
//alertDialog.show();
}
private void fetchingAddsFromServer() {
StringRequest request= new StringRequest(URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object= new JSONObject(response);
JSONArray jsonArray=object.getJSONArray("slots");
JSONObject jsonObject=jsonArray.getJSONObject(1);
Toast.makeText(MainActivity.this, "Image Url
is:"+jsonObject.getString("imgurl"), Toast.LENGTH_LONG).show();
// String ImgURI=jsonObject.getString("imgurl");
Glide.with(getApplicationContext()).load(jsonObject.getString("imgurl")).into(c
losingDialogImageTwo);
//}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue= Volley.newRequestQueue(MainActivity.this);
queue.add(request);
I think its an error of custom layout.I have one ImageView in main screen. if i use Glide with that it is working fine but if a use Glide with custom layout of dialog it gives me this error that is mentioned.
The following error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.madnanijaz.labassignment1, PID: 2967
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:22)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:383)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:181)
at com.example.madnanijaz.labassignment1.MainActivity$7.onResponse(MainActivity.java:170)
happens because you're trying to loading the image to closingDialogImageTwo with this:
Glide.with(getApplicationContext()).load(jsonObject.getString("imgurl")).into(c losingDialogImageTwo);
but you haven't initialize the View yet. Because the image is inside the custom view for the dialog, you need to initialize it after you inflating the view. Which is after the following code:
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
with this:
ImageView closingDialogImageTwo = view.findViewById(R.id.your_image_id);
You need to load the image only after your fetchingAddsFromServer() method finished fetching the image because its asynchronous behaviour.
To summarize, you need to move your AlertDialog creation inside the fetchingAddsFromServer like this:
private void fetchingAddsFromServer() {
StringRequest request= new StringRequest(URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
// assuming you got the image.
String imageUrl = jsonObject.getString("imgurl");
showDialogWithImage(imageUrl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue= Volley.newRequestQueue(MainActivity.this);
queue.add(request);
}
private void showDialogWithImage(String imageUrl) {
final AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_layout,null);
ImageView closingDialogImageTwo = view.findViewById(R.id.your_image_id);
Glide.with(getApplicationContext())
.load(imageUrl).into(closingDialogImageTwo);
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setView(view);
builder.show();
}
Related
I keep getting this Error in my ListActivity.java
public void deleteData(int index){
pd.setTitle("Deleting data...");
pd.show();
db.collection("Documents").document(modelList.get(index).getId())
.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
pd.dismiss();
Toast.makeText(ListActivity.this, "Deleted", Toast.LENGTH_SHORT);
showData();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(ListActivity.this,e.getMessage(), Toast.LENGTH_SHORT);
}
});
}
When i tried calling deleteData under customanother.java it cannot resolve method delete data in my ListActivity.java
Can someone help me to fix this? this is my first time in android studio to develop a simple crud app with firebase. My update, edit function works just fine but in my delete button idk why it cannot resolve the method.
heres my code in CustomAdapter.java
public void onItemLongClick(View view, int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(listActivity);
String[] options = {"Update/Print", "Delete"};
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if ( which == 0){
String id = modelList.get(position).getId();
String title = modelList.get(position).getTitle();
String description = modelList.get(position).getDescription();
Intent intent = new Intent(listActivity, MainActivity.class);
intent.putExtra("pId",id);
intent.putExtra("pTitle",title);
intent.putExtra("pDescription",description);
listActivity.startActivity(intent);
}
if (which ==1){
listActivity.deleteData(position);
}
}
}).create().show();
}
});
Am i missing something?
Hello as mention in the error you try pass com.example.sample.ListActivity as android.app.ListActivity so the simple solution to change the import of your activity to become compatible
I am trying to make my own Alert dialogs using "utility" class that extends AppCompatDialogFragment. But when I try to set my own messages, they didn't change, but the default ones of the class I created continue to appear.
For example in my AlertDialogConnection class I made Override of onCreateDialog, but in my activity, while I perform http request, I can't make my own texts.
My own class that extends AppCompatDialogFragment
public class AlertDialogConnection extends AppCompatDialogFragment {
private Builder builder;
private String title;
private String text;
public AlertDialogConnection(){
this.builder = null;
this.text = "";
this.title = "";
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if((this.title == "") || (this.text == "") || (this.builder == null)){
this.builder = new Builder(getActivity());
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder = new Builder(getActivity());
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
public void setTitle(String title){
this.title = title;
}
public void setText(String text){
this.text = text;
}
}
Some code using that class
in this class, in case of error I continue to see the default error of the class AlertDialogConnection, instead of my serverError title and text.
private AlertDialogConnection serverError = new AlertdialogConnection();
private void requestData(String url) throws MalformedURLException {
Request request = new Request.Builder().url(url).build();
final Intent intent = new Intent(this, ModelResultData.class);
httpClient.connectTimeoutMillis(); //server timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("HTTP-Error", "HTTP request error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server messaging error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
ModelSearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("ACTIVITY_SOURCE", "ModelSearchActivity");
intent.putExtra("json_data", body);
startActivity(intent);
}
});
}else{
//System.out.println(response.code());
//if (response.code() == 403) {
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
//} else if (response.code() == 500) {
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error, try later");
serverError.show(getSupportFragmentManager(), "server error!");
//}
}
}
});
}
I have tried making comparisons with response code, but nothing change.
The default value (in the constructor) you've set for builder is null.
This causes it to always get through the if condition since builder == null would return true. Try something along the following lines,
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.builder = new Builder(getActivity());
if(this.title.isEmpty() || this.text.isEmpty()){
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
You don't need to have a separate utility for creating your own alert dialogue you can simply create a view and use the setView method to show that view in your app. See the snippet below
private void showDialog()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.sortdialog,null);//Replace it
alertDialogBuilder.setView(view);
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
This will allow you to create custom alert dialog boxes using the layout which you have created
By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated
Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);
I get this error every once in a while and not sure how to fix it. I read that the context could be destroyed but no REAL answers on how to solve it, especially for my situation.
The error happens below on Utility.showDialog in the onPostExecute on my BaseLoadOperation. What is the correct way to handle this?
DataTask.java
public class DataTask extends BaseLoadOperation {
public DataTask(Context context) {
super(context);
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
Utility.showDialog(this.context.getString(R.string.connectionerror), "OK", this.context);
}
Utility.java
public static void showDialog(String message, String buttonText, Context context, final IDialogCallback callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(buttonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(callback != null)
{
callback.buttonPress();
}
}
});
AlertDialog alert = builder.show();
TextView messageText = (TextView)alert.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
alert.show();
}
Exception android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#49fff91 is not valid; is your activity running?
android.view.ViewRootImpl.setView (ViewRootImpl.java:900)
android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:342)
android.view.WindowManagerImpl.addView (WindowManagerImpl.java:97)
android.app.Dialog.show (Dialog.java:419)
android.support.v7.app.AlertDialog$Builder.show (AlertDialog.java:956)
com.exposure.utilities.Utility.showDialog (Utility.java:196)
com.exposure.utilities.Utility.showDialog (Utility.java:181)
com.exposure.utilities.DataTask.onPostExecute (DataTask.java:44)
Am new to android and i have successfully manged to show data from mysql database in a list and set an alert dialog for when an item is clicked.The Alert dialog has to take in a comment about the item clicked and send it to the mysql database but am stuck at making the connection.
Here is my code
public void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String idnum = c.getString(TAG_IDNUM);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_FNAME,fname);
persons.put(TAG_LNAME,lname);
persons.put(TAG_IDNUM,idnum);
personList.add(persons);
}
final ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, personList, R.layout.list_activity,
new String[]{TAG_ID,TAG_FNAME,TAG_LNAME,TAG_IDNUM},
new int[]{R.id.id, R.id.textViewFname, R.id.textViewLname,R.id.textViewIdnum}
);
list.setAdapter(adapter);
//alert dialog
//Create onclick listener class
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Alert id: "+TAG_IDNUM); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting Added", Toast.LENGTH_LONG).show();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}
So i managed to come up with the following but the variables am sending to the php file don't seem to be getting there.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
final String id_number =((TextView)view.findViewById(R.id.textViewIdnum)).getText().toString();
alert.setTitle("Alert id: "+id_number); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String reason = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting...", Toast.LENGTH_LONG).show();
final String reason_key = input.getText().toString().trim();
//final String id_number_key = textview;
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.RESULT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(SearchActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SearchActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
Map<String,String> params = new HashMap<String, String>();
params.put(TAG_IDNUM,id_number);
params.put(reason_key,reason);
RequestQueue requestQueue = Volley.newRequestQueue(SearchActivity.this);
requestQueue.add(stringRequest);
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}