This is the register fiile:
The error is when I stored data and after that, I log in when I click on the login button app got crushed.
this is the register section;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText textview1;
EditText textview2;
Button button1;
Button buttonlog;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (EditText)findViewById(R.id.ediuser);
textview2 = (EditText)findViewById(R.id.edipassword);
button1 = (Button)findViewById(R.id.btnreg);
buttonlog = (Button)findViewById(R.id.onlogin);
}
public void onreg(View view){
String username = textview1.getText().toString();
String Password = textview2.getText().toString();
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
editor1.putString("username",username);
editor1.putString("password",Password);
editor1.apply();
Toast.makeText(this, "Register Successfully", Toast.LENGTH_SHORT).show();
}
public void onlog(View view){
Intent intent = new Intent(this,login.class);
startActivity(intent);
}
}
this is the login file:
package com.example.newshrd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
EditText editText1;
EditText editText2;
Button button2;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText1 = (EditText) findViewById(R.id.userlog);
editText2 = (EditText) findViewById(R.id.passwordlog);
button2 = (Button) findViewById(R.id.btnlog);
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
}
//this is the login section find error and let me know please
public void onloghere(View view){
String userlog = editText1.getText().toString();
String passlog = editText2.getText().toString();
String userlogin= sharedPreferences.getString("username",null);
String userpaswwords=sharedPreferences.getString("passowrd",null);
if (userlog.contains(userlogin) && passlog.contains(userpaswwords)){
Toast.makeText(this, "Your are in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You are not", Toast.LENGTH_SHORT).show();
}
}
}
please, someone, find the error and let me know what I am missing in this code.
It is properly formatted (at least by the preview it is), so how can I fix this? I'm new to Stack Overflow formatting.
When you save, key is "password":
editor1.putString("password",Password);
But when get, you have a typo for the key here "passowrd":
String userpaswwords=sharedPreferences.getString("passowrd",null);
The userpaswwords you get is null (you set SharedPreferences.getString(String key, #Nullable String defValue) defValue value to be null), and here crashes:
passlog.contains(userpaswwords)
Cuz String.contains(CharSequence s) needs the argument to be non-null.
I am creating quiz app from volley library in android. where I get data in Array list from external website. now problem is that how to set data in Textview and Buttons. I created one Textviewfor show question, four Buttions for options, and Two more Buttions for go to next question and go to previous question. here is image
I want that when i click one of the option button than his color will be blue and rest of button will be grey. when i click next button than load new question and all options button will be grey.
here is my main activity.java code. please help me in create quiz app.
package com.ravindra.excelrecycleview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private QuestionAdapter mQuestionAdatpter;
private ArrayList<question> mquestion;
private RequestQueue mRequestQueue;
ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recylcer_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mquestion = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
loading = ProgressDialog.show(this,"Loading","please wait",false,true);
String url ="https://script.google.com/macros/s/AKfycbw6eHqtKTxHoS9HPSdfTasY-iebLQXUgS3sHHiOpeuGxJfssBI/exec?action=getQuestions";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i =0;i<jsonArray.length();i++){
JSONObject items = jsonArray.getJSONObject(i);
String questions = items.getString("questions");
String optiona = items.getString("optiona");
String optionb = items.getString("optionb");
String optionc = items.getString("optionc");
String optiond = items.getString("optiond");
String correctans = items.getString("correctans");
String explain = items.getString("explain");
mquestion.add(new question(questions,optiona,optionb,optionc,optiond,correctans,explain));
}
mQuestionAdatpter = new QuestionAdapter(MainActivity.this,mquestion);
mRecyclerView.setAdapter(mQuestionAdatpter);
loading.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
} );
mRequestQueue.add(request);
int socketTimeOut = 50000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
}
}
I'm creating an event app which contains a list of events in recyclerview.
The events recyclerview consists of the event name, image, date and time, heart image (example: heart shape like button on Instagram) which will change its color when the user clicks on the 'interested' button.
After clicking on any event its description appears and there are two buttons: 'interested' and 'going'. If the user clicks on 'interested' that heart color in the recyclerview will become yellow. The event will also get saved in another list where it will remain until that event is removed from the saved list.
So far I've completed saving that event in the saved list on clicking the 'interested' button. But I don't know how to change the heart color simultaneously and how to make it remain until the event is deleted from saved list.
First Activity calling recyclerview adapter
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class EventActivity extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static final String URL_PRODUCTS = "https://www.test.magicalballoons.co.in/priyanka/event.php?";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
ImageView homemenu;
//SwipeRefreshLayout swiper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
getSupportActionBar().hide();
homemenu = findViewById(R.id.homemenu);
// swiper = findViewById(R.id.swiper);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getString("id"),
product.getString("name"),
product.getString("date"),
product.getString("location"),
product.getString("image"),
product.getString("details")
));
}
//creating adapter object and setting it to recyclerview
RecyclerViewAdapter adapter = new RecyclerViewAdapter(EventActivity.this, productList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EventActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void onBackPressed() {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Recyclerview Adapter
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.BreakIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static com.example.priyankaregistration.URLs.URL_EVENT;
/**
* Created by Aws on 11/03/2018.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private RequestQueue requestQueue;
private JsonArrayRequest request;
private Context mContext;
private List<Product> mData;
RequestOptions option;
TextView total;
ImageView colorheart,heart;
// Dialog myDailog;
private Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<Product> mData) {
this.mContext = mContext;
this.mData = mData;
//this.swiper = swiper;
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.fragment_conferences, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
myDialog = new Dialog(mContext);
colorheart = (ImageView) view.findViewById(R.id.colorheart);
heart = (ImageView) view.findViewById(R.id.heart);
total = (TextView) view.findViewById(R.id.count);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_COUNT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
total.setText(jsonObject.getString("countid"));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("eventid", mData.get(viewHolder.getAdapterPosition()).getId());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, Description.class);
intent.putExtra("eventname",mData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra("eventid",mData.get(viewHolder.getAdapterPosition()).getId());
intent.putExtra("eventdate",mData.get(viewHolder.getAdapterPosition()).getDate());
intent.putExtra("eventloc",mData.get(viewHolder.getAdapterPosition()).getLocation());
intent.putExtra("eventimg",mData.get(viewHolder.getAdapterPosition()).getImage());
intent.putExtra("details",mData.get(viewHolder.getAdapterPosition()).getDetails());
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textViewName.setText(mData.get(position).getName());
holder.textViewDate.setText("Date : " + mData.get(position).getDate());
holder.textViewLocation.setText("Time : " + mData.get(position).getLocation());
Glide.with(mContext).load(mData.get(position).getImage()).apply(option).into(holder.img_thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewName,textViewDate, textViewLocation,total;
ImageView img_thumbnail;
//LinearLayout view_container;
CardView view_container;
public MyViewHolder(View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.container);
textViewName = itemView.findViewById(R.id.textViewName);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewLocation = itemView.findViewById(R.id.textViewLocation);
total = itemView.findViewById(R.id.count);
img_thumbnail=itemView.findViewById(R.id.imageView);
}
}
}
This is second activity
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Description extends AppCompatActivity {
TextView textViewName,textViewDate, textViewLocation, details;
ImageView evimg,going,interest;
RequestOptions option;
ImageView homemenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
getSupportActionBar().hide();
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
textViewName = findViewById(R.id.textViewName);
evimg = findViewById(R.id.evimg);
details = findViewById(R.id.details);
going = findViewById(R.id.going);
interest = findViewById(R.id.interest);
homemenu = findViewById(R.id.homemenu);
textViewName.setText(getIntent().getStringExtra("eventname"));
//textViewDate.setText(getIntent().getStringExtra("eventdate"));
//textViewLocation.setText(getIntent().getStringExtra("eventloc"));
details.setText(getIntent().getStringExtra("details"));
details.setMovementMethod(new ScrollingMovementMethod());
Glide.with(this).load(getIntent().getStringExtra("eventimg")).apply(option).into(evimg);
going.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_EVENT+"?userid=" + SharedPrefManager.getInstance(getApplicationContext()).getUserId() + "&eventid="+ getIntent().getStringExtra("eventid"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("name");
Intent intent = new Intent(Description.this,Ticket.class);
intent.putExtra("code",message);
intent.putExtra("eventimg",getIntent().getStringExtra("eventimg"));
intent.putExtra("activity","NO");
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
jsonrequest();
startActivity(intent);
finish();
//Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
//params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTSAVED ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
//String message = jsonObject.getString("name")
Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Description.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void jsonrequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTDELETED,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(),jsonObject.getString("Event removed from saved list"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
//progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
I'm having heart image in my recyclerview . And when i click on interest buttton in Description activity the heart image in recyclerview get change.
Assuming you are saving the events in some model class, what you can do is when calling the onBindViewHolder method of your adapter, check if the event is marked as save. If it is, then you either need to change the heart image to another heart image which is yellow, or you can apply a tint on the heart image to make it yellow.
You can change drawable by using this code
heartImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_heart));
You can apply tint by using this code
heartImageView.setColorFilter(Color.argb(255, 255, 255, 0))
EDIT (Based on comment)
If the heart is in the first activity and the interested button is in the second activity what you need to do is to save the state of the event when you click on the interested button. Once you go back to the the first activity, you can check the state of the event and then update the image by using any of the above two methods.
EDIT 2 (Based on new code shared)
After you get the response from your Volley call, you should save the event id somewhere to keep track of which events you are interested in (this can be in either a model class or some global list). When you go back to your first activity (which contains the recyclerview), you need to check each event id with the stored event id list that you have and change the heart for each event that matches.
You can do this with the help for startActivityforresult
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult for sending data back:
Intent intent = new Intent();
intent.putExtra("updatedArraylist", "arraylist")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult:
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strArrayList =
data.getStringExtra("updatedArraylist");
Gson gson = new Gson();
Type youListType = new TypeToken<List<Model>>() {
}.getType();
List<Model> yourTypeList = gson.fromJson(strArrayList,
yourListType);
ArrayList finalArraylist = new ArrayList<>(yourTypeList);
yourArraylist.addAll(finalArraylist);
youtAdapter.notifyDataSetChanged();
}
}
}
You can apply color onclick event to heart button like following code :
your_image_id.setBackgroundColor(getResources().getColor(R.color.yellow));
In first activity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 100);
From second activity, you have to execute the below code before the activity getting destroyed by finish() or back press (For this you can override onBackPressed of second activity and remove the super class call and call the below method).
private void exitWithResult(){
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Id of selected item");
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
Again in first activity you have to handle the result inside onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.e("DATA", "" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
Log.e("DATA", "No result");
}
}
}
Update
You can use an interface as callback from adapter to activity. startActivityForResult canbe called inside the callback method of interface. You have to pass callback interface to adapter through adapter constructor along with data set.
declare this interface inside adapter
public interface AdapterCallback{
void onAdapterSelected(int pos);
}
And in first activity implement the interface like this.
MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
#Override
public void onAdapterSelected(int pos) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivityForResult(intent, 100);
}
};
Then set adapter like this.
RecyclerView rv = findViewById(R.id.rv_list);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
MyAdapter adapter = new MyAdapter(callback); //This is the only change
rv.setAdapter(adapter);
Changes in adapter below. (You should pass list data along with call back as you already does)
private AdapterCallback callback;
public MyAdapter(AdapterCallback callback) {
this.callback = callback;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int i) {
viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onAdapterSelected(i);
}
});
}
Interface also come inside adapter. I am not repeating it here as i already mentioned at first
While trying to build a texting app and I added a Firebase value event listener which is called from onCreate() (...callFirebase() function), all of this looked good to me before I realised my RecyclerView stopped updating itself (..messageAdapter.notifyItemInserted(messageList.size()-1)) when I pressed the send button. And RecyclerView starts working properly as soon as I comment the callFirebase() line in onCreate(). Please look at the code and let me know that I did wrong.
package com.siddhantkushwaha.www.raven;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class chat_room extends AppCompatActivity {
private FloatingActionButton sendButton;
private EditText chatEditText;
private String uid_1;
private String uid_2;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;
private RecyclerView recyclerView;
private String threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
uid_1 = intent.getStringExtra("sender");
uid_2 = intent.getStringExtra("receiver");
sendButton = findViewById(R.id.sendButton);
chatEditText = findViewById(R.id.chatEditText);
recyclerView = findViewById(R.id.messageRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
messageList = new ArrayList();
messageAdapter = new MessageAdapter(this, messageList, uid_1);
recyclerView.setAdapter(messageAdapter);
callFirebase();
}
private void callFirebase() {
threadId = null;
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_1) + "/" + uid_2).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
threadId = dataSnapshot.getValue().toString();
System.out.println(threadId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStart() {
super.onStart();
}
public void sendButtonClicked(View view) {
sendMessage();
}
private void sendMessage() {
String text_message = chatEditText.getText().toString();
if(text_message.length() == 0)
return;
messageList.add(new Message(text_message, uid_1, uid_2));
messageAdapter.notifyItemInserted(messageList.size()-1);
recyclerView.smoothScrollToPosition(messageAdapter.getItemCount());
chatEditText.setText("");
if(threadId != null) {
addToThread(new Message(text_message, uid_1, uid_2));
}
else {
createThread(new Message(text_message, uid_1, uid_2));
}
}
private void createThread(Message _message) {
String thread_key = Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsRoot()).push().getKey();
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadDetails(thread_key)).setValue(new ThreadDetails(uid_1, uid_2));
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadMessageList(thread_key)).push().setValue(_message);
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_1) + "/" + uid_2).setValue(thread_key);
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadsList(uid_2) + "/" + uid_1).setValue(thread_key);
threadId = thread_key;
}
private void addToThread(Message _message) {
Util.getDatabase().getInstance().getReference(PathUtil.pathToThreadMessageList(threadId)).push().setValue(_message);
}
}
This is happening because you are assigning a value to the threadId variable inside the onDataChange() method and you trying to use it outside that method. Just declaring a variable as global doesn't solve your problem because onDataChange() method has asynchronous behaviour, which means that is called even before you are trying to get the data from the database. A quick fix would be to use that variable only inside that method, or to use the last part of my answer from this post. I also recommend you see this video.
when using the ab.jar in eclipse I get the following error when trying to run the bot.
“Could not find class ‘org.alicebot.ab.Bot’, referenced from method…”. The chat class is being imported but the bot class cannot be imported.
Here is my code:
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends Activity {
String usertext; String response;
String botname="MAVIS";
Bot mavis=new Bot(botname);
Chat chat= new Chat(mavis);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout ll1 = (LinearLayout) findViewById(R.id.ll1);
final LinearLayout ll2 = (LinearLayout) findViewById(R.id.ll2);
final ScrollView scv = (ScrollView) findViewById(R.id.sv);
final Button btn = (Button) findViewById(R.id.button1);
final EditText medit = (EditText) findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
TextView tvu=new TextView(v.getContext());
TextView tvb=new TextView(v.getContext());
TextView tvut=new TextView(v.getContext());
TextView tvbt=new TextView(v.getContext());
TextView tvdivider1=new TextView(v.getContext());
TextView tvdivider2=new TextView(v.getContext());
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tvu.setLayoutParams(lparams);
tvb.setLayoutParams(lparams);
tvut.setLayoutParams(lparams);
tvbt.setLayoutParams(lparams);
tvdivider1.setLayoutParams(lparams);
tvdivider2.setLayoutParams(lparams);
usertext = medit.getText().toString();
if(usertext.trim().length() != 0){
ll1.addView(tvu);
ll1.addView(tvb);
ll2.addView(tvut);
ll2.addView(tvbt);
ll1.addView(tvdivider1);
ll2.addView(tvdivider2);
response=chat.multisentenceRespond(usertext);
tvu.setText("User");
tvb.setText(botname);
tvbt.setText(" : "+ response);
tvut.setText(" : "+ usertext);
medit.setText(" ");
tvdivider1.setText(" ");
tvdivider2.setText(" --------------------");
}
else{
//do nothing
}
}
});
scv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
scv.post(new Runnable() {
public void run() {
scv.fullScroll(View.FOCUS_DOWN);
}
});
}
});
}
}
I have imported the external library and defined the classpath for it. I have also copied the ab.jar in my project folder and even defined the classpath for it. But nothing seems to be working. Am I doing this wrong or are there more libraries that are needed for this to work. Anybody have a solution to my problem?
Your bot name here is MAVIS..did you change the folder name from the bots.zip???else change it..or simply use the predefined bot names(alice2 etc).
Thankz