how pass result from alertDialog to onActivityResult - java

I have Activity_A an Activity_B.
I use onActivityResult and i have a problem:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=3, result=-1, data=Intent { (has extras)
}} to activity {com.example.sellcar/com.example.sellcar.View_Offer}:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
I guess that I can not pass this way 'result' from alertDialog to onActivityResult.
I do not know how to solve this problem :/
Please help
Activity_A:
bBUTTON.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity_A.this,Activity_B.class);
startActivityForResult(intent, 3);
}
});
...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK){
String pId = data.getStringExtra("MyData");
Toast.makeText(Activity_A.this,pId,Toast.LENGTH_LONG).show();
}
}
Activity_B:
AlertDialog.Builder builder=new AlertDialog.Builder(View_Sell.this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
Intent intent = new Intent();
intent.putExtra("MyData", ostatnioDodanaSprzedaz);
setResult(RESULT_OK, intent);
onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
AlertDialog ad = builder.create();
ad.show();

Try to replace:
setResult(RESULT_OK, intent);
onBackPressed();
on:
if (getParent() == null) {
setResult(RESULT_OK, intent);
} else {
getParent().setResult(RESULT_OK, intent);
}
finish();

You can follow the Observer pattern.
First, create an Interface in the Activity class itself:
public interface ResultListener {
void onResultSet(String text);
}
Then, create an object of ResultListener globally:
ResultListener = rl;
Implement the onResultSet(String text) method inside the onCreate method:
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
Next, create the AlertDialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
tl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
Here's how the final code will look:
public class MainActivity extends Activity {
ResultListener rl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
rl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
} //onCreate closed
public interface ResultListener {
void onResultSet(String text);
}
} //MainActivity Class closed

Related

RecyclerView doesn't refresh after Firebase update

I have a RecyclerView and for each item, you can start the EditActivity (for Result) to update your text with Firebase.
The problem is that when you come back to the RecyclerView, data is not refreshed
Here's code from my adapter :
holder.editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent edit_intent = new Intent(holder.authorText.getContext(), EditActivity.class);
edit_intent.putExtra("text", textList.get(position).getBody());
edit_intent.putExtra("id", textList.get(position).textId);
((Activity) context).startActivityForResult(edit_intent, 1);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
notifyDataSetChanged();
}
}
}
Here's code from my EditActivity :
edit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgress.setVisibility(View.VISIBLE);
edit_btn.setVisibility(View.INVISIBLE);
String new_text = edit_text.getText().toString();
mFirestore.collection("Text").document(text_id).update("body", new_text).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(EditActivity.this, R.string.changes, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("newText", new_text);
setResult(RESULT_OK, intent);
finish();
}
else{
String error = task.getException().getMessage();
Toast.makeText(EditActivity.this, R.string.error + error, Toast.LENGTH_LONG).show();
}
mProgress.setVisibility(View.INVISIBLE);
edit_btn.setVisibility(View.VISIBLE);
}
});
}
});
How to refresh the RecyclerView and setText with the new Text ?
I would be very grateful for your help :)
There are few things you're doing wrong.
Pass the clickedItem position to EditActivity to update it later on.
holder.editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent edit_intent = new Intent(holder.authorText.getContext(), EditActivity.class);
edit_intent.putExtra("text", textList.get(position).getBody());
edit_intent.putExtra("id", textList.get(position).textId);
edit_intent.putExtra("position", position);
((Activity) context).startActivityForResult(edit_intent, 1);
}
});
In EditActivity, Save the position in a variable & Return it back with new text
setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgress.setVisibility(View.VISIBLE);
edit_btn.setVisibility(View.INVISIBLE);
String new_text = edit_text.getText().toString();
mFirestore.collection("Text").document(text_id).update("body", new_text).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(EditActivity.this, R.string.changes, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("newText", new_text);
//Return the position s well
intent.putExtra("position", position);
setResult(RESULT_OK, intent);
finish();
}
else{
String error = task.getException().getMessage();
Toast.makeText(EditActivity.this, R.string.error + error, Toast.LENGTH_LONG).show();
}
mProgress.setVisibility(View.INVISIBLE);
edit_btn.setVisibility(View.VISIBLE);
}
});
}
});
override onActivityResult() in your adaptor's parent activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String newText = data.getStringExtra("newText");
int itemPosition = data.getIntExtra("position");
//Pass these values to adapter through `updateItem` method
adapter.updateItem(newText, itemPosition);
}
}
}
Define the updateItem method inside adapter class
public void updateItem(String newData, int index)
{
textList.set(index, newData);
adapter.notifyItemChanged(index);
}
Cheers :)

URL result in scanner

I'm still new at programming and I tried to build a code scanner for my project.
The problem is the result only show a text. It can't be click or direct to browser.
public class ReaderActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
Button scan_btn = findViewById(R.id.scan_btn);
final Activity activity = this;
IntentIntegrator qrScan = new IntentIntegrator(this);
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
can somebody fix this?
you can check if result.getContents() start with "http" or "https" use string.indexOf, get it and put to your browser.

Activity does not even call onActivityResult

I know,I have seen the duplicates. But none of them solved my issue.
I want my code to get newMessage from EditMessage activity and pass it to the SendMessage Activity, and I know I may not need to use onActivityResult tough I still want to learn what's the issue here.
I'have added log messages to check where my problem is but it doesn't even run my Log inside the onActivityResult.
Here's the code:
EditMessageActivity:
public static final String MESSAGE = "message";
EditText currentTextEditText;
Button sendButton;
Button saveButton;
Button cancelButton;
Button concatenateButton;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_message_layout);
message = getIntent().getStringExtra(SendMessageActivity.MESSAGE);
currentTextEditText = (EditText) findViewById(R.id.currentText_EditText);
sendButton = (Button) findViewById(R.id.sendButton);
saveButton = (Button) findViewById(R.id.saveButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
concatenateButton = (Button) findViewById(R.id.concatenateButton);
if (message != null) //Activity may be started via "edit" Button
currentTextEditText.setText(message);
currentTextEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
message = currentTextEditText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
message = currentTextEditText.getText().toString();
}
});
concatenateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String[] messages = getResources().getStringArray(R.array.messages_array);
AlertDialog.Builder builder = new AlertDialog.Builder(EditMessage.this);
builder.setTitle("Sonuna Ekle").setItems(messages, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
char lastChar = message.charAt(message.length() - 1);
String messageToAdd = messages[which];
if (lastChar == '!' || lastChar == '?' || lastChar == '.') {
message += " " + messageToAdd;
} else {
message += " " + messageToAdd.toLowerCase();
}
currentTextEditText.setText(message);
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EditMessage.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
finish();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessage.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK);
startActivityForResult(intent, SendMessageActivity.REQUEST_NEW_MESSAGE);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
SendMessageActivity:
public static final String MESSAGE = "message";
public static final int REQUEST_NEW_MESSAGE = 1001;
private static String message;
ListView messageListView;
Button createMessage;
ArrayList<String> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
//Retrive Pre-Defined Messages
//TODO Add in-app message defining
String[] dbMessages = getResources().getStringArray(R.array.messages_array);
for (int i = 0; i < dbMessages.length; i++) {
messageList.add(dbMessages[i]);
}
//Create the array adapter
//TODO Upgrade this to a custom adapter which will also show an small image related to the message
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
createMessage = (Button) findViewById(R.id.createMessageBtn);
createMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startEditMessage("");
}
});
messageListView = (ListView) findViewById(R.id.messagesListView);
messageListView.setAdapter(adapter);
//Make this one clickable
messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
message = messageList.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(SendMessageActivity.this);
builder.setTitle("Send Message");
builder.setMessage(message);
builder.setPositiveButton("Gönder", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(SendMessageActivity.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
});
builder.setNeutralButton("Düzenle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Create new activity to edit message and send it or just cancel it
//Todo and return back
startEditMessage(message);
}
});
builder.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Custom", "Result OK değil :" + message);
if (resultCode == RESULT_OK) {
Log.i("Custom","Result OK:" + message);
if (requestCode == REQUEST_NEW_MESSAGE) {
Log.i("Custom","request is ok :" + message);
String newMessage = getIntent().getStringExtra(EditMessage.MESSAGE);
if (newMessage != null) {
Log.i("Custom","Message is not null :" + message);
messageList.add(newMessage);
//TODO Create new method to load all messages from database and just call that method
ArrayAdapter<String> updatedAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
messageListView.setAdapter(updatedAdapter);
Log.i("Custom", "Updated adapter :" + message);
}
}
}
}
public void startEditMessage(String message) {
Intent intent = new Intent(SendMessageActivity.this, EditMessage.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
Any help will be appriciated.Thanks.
I want my code to get newMessage from EditMessage activity and pass it
to the SendMessage Activity.
Lets say there are three activities A(MainActivity), B(EditMessageActivity), C(SendMessageActivity).
To get message from B to A, you startActivityForResult() from A. When required value is retreived in B, you setResult() in B and then call finish().
The result will be received in A by overriding onActivityResult(). And then start C, and put the value in intent.
For example, reporting value back to MainActivity from EditMessageActivity:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent();
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK, intent);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
If there are only two activities, then no need of onActivityResult(). You can directly pass the message to SendMessageActivity using Intent.
For example, sending value from MainActivity to EditMessageActivity without onActivityResult():
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessageActivity.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
Log.i("Custom", "Custom Message created :" + message);
}
});
Use
int request = 0;// Any number to identify your request
startActivityForResult(intent,request);
Instead of
startActivity(intent);
And don't use
finish()
;// function from the calling activity which will remove the activity from the stack.

how to reload main activity after click "OK" on AlertDialog

I have an AlertDialog and I want the Main Activity to reload after I have click "OK". The problem is after I have click OK my activity returned to the home screen.
JAVA Code :
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"This application needs GPS satellite or Wireless Networks localization enabled"
+ "\n" + "Do you want to enable it?")
.setCancelable(true)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
startActivity(getIntent());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
Help would be appreciated.
Change this code
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
startActivity(getIntent());
}
to
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivityForResult(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
Call onCreate method again. But pass null as a parameter.
onCreate(null);

App crashing on count and dialog box

i am using following code.
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
displayAlertForRestart();
}
#Override
public void onTick(long millisUntilFinished)
{
counter.setText("Time Left: " + millisUntilFinished/1000 + " sec");
}
}
public void displayAlertForRestart()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage("Do you want to Restart?");
builder.setTitle("Game Over");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(context,Level.class);
startActivity(myIntent);
dialog.dismiss();
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
LogCat error: Error at alert.show();
36: E/AndroidRuntime(9829): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#43cf1e38 is not valid; is your activity running?
change your code like this
public class MyCount extends CountDownTimer
{
Context mContext;
public MyCount(long millisInFuture, long countDownInterval,Context context)
{
super(millisInFuture, countDownInterval);
mContext=context;
}
#Override
public void onFinish(Context context)
{
displayAlertForRestart(context);
}
#Override
public void onTick(long millisUntilFinished)
{
counter.setText("Time Left: " + millisUntilFinished/1000 + " sec");
}
}
public void displayAlertForRestart(Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setMessage("Do you want to Restart?");
builder.setTitle("Game Over");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(context,Level.class);
startActivity(myIntent);
dialog.dismiss();
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if your countdown is not finished, you must FIRST FINISH it before finishing the activity.
Try this, myCount.cancel when you finish the activity.

Categories