I'm following Mesibo Tutorial for the First App and trying to integrate it in my app. The difference to the source code of tutorial https://github.com/mesibo/samples/tree/master/android/java/FirstApp is only that I have implemented it in Fragment instead of Activity and using databinding for views.
Every time if I'm clicking to LOGIN_AS_USER1 or LOGIN_AS_USER2 Button it shows connection Status 5. The created users are never online.
The users with corresponding user addresses and app ID (app Package) were created manually in Mesibo console. Tokens, addresses and app ID are double checked.
My Fragment code:
public class CommunicationFragment extends Fragment implements Mesibo.ConnectionListener, Mesibo.MessageListener {
private FragmentCommunicationBinding binding;
class DemoUser {
public String token;
public String name;
public String address;
DemoUser(String token, String name, String address) {
this.token = token;
this.name = name;
this.address = address;
}
}
//Refer to the Get-Started guide to create two users and their access tokens
DemoUser mUser1 = new DemoUser("631b138a5bfd2827b20d312721ee6549198539a5041517df2e33311958", "User-1", "1233");
DemoUser mUser2 = new DemoUser("ae80d38f59a814b3f4694055bbd90005c2fdae2ae7a530fe44311959", "User-2", "4566");
DemoUser mRemoteUser;
Mesibo.UserProfile mProfile;
Mesibo.ReadDbSession mReadSession;
Button mSendButton, mUiButton, mAudioCallButton, mVideoCallButton;
Button mLoginButton1, mLoginButton2;
TextView mMessageStatus, mConnStatus;
EditText mMessage;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_communication, container, false);
View view = binding.getRoot();
mLoginButton1 = binding.login1;
mLoginButton2 = binding.login2;
mSendButton = binding.send;
mUiButton = binding.launchUI;
mAudioCallButton = binding.audioCall;
mVideoCallButton = binding.videoCall;
mMessageStatus = binding.msgStatus;
mConnStatus = binding.connStatus;
mMessage = binding.message;
mSendButton.setEnabled(false);
mUiButton.setEnabled(false);
mAudioCallButton.setEnabled(false);
mVideoCallButton.setEnabled(false);
mLoginButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mesiboInit(mUser1, mUser2); }
});
mLoginButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mesiboInit(mUser2, mUser1); }
});
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mesibo.MessageParams p = new Mesibo.MessageParams();
p.peer = mRemoteUser.address;
p.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT;
Mesibo.sendMessage(p, Mesibo.random(), mMessage.getText().toString().trim());
mMessage.setText("");}
});
mUiButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboUI.launchMessageView(getActivity(), mRemoteUser.address, 0);
}
});
mAudioCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboCall.getInstance().callUi(getActivity(), mProfile.address, false);
}
});
mVideoCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboCall.getInstance().callUi(getActivity(), mProfile.address, true);
}
});
return view;
}
private void mesiboInit(DemoUser user, DemoUser remoteUser) {
Mesibo api = Mesibo.getInstance();
api.init(getActivity().getApplicationContext());
Mesibo.addListener(this);
Mesibo.setSecureConnection(true);
Mesibo.setAccessToken(user.token);
Mesibo.setDatabase("mydb", 0);
Mesibo.start();
mRemoteUser = remoteUser;
mProfile = new Mesibo.UserProfile();
mProfile.address = remoteUser.address;
mProfile.name = remoteUser.name;
Mesibo.setUserProfile(mProfile, false);
// disable login buttons
mLoginButton1.setEnabled(false);
mLoginButton2.setEnabled(false);
// enable buttons
mSendButton.setEnabled(true);
mUiButton.setEnabled(true);
mAudioCallButton.setEnabled(true);
mVideoCallButton.setEnabled(true);
MesiboCall.getInstance().init(getActivity().getApplicationContext());
// Read receipts are enabled only when App is set to be in foreground
Mesibo.setAppInForeground(getActivity(), 0, true);
mReadSession = new Mesibo.ReadDbSession(mRemoteUser.address, this);
mReadSession.enableReadReceipt(true);
mReadSession.read(100);
}
#Override
public void Mesibo_onConnectionStatus(int status) {
mConnStatus.setText("Connection Status: " + status);
}
#Override
public boolean Mesibo_onMessage(Mesibo.MessageParams messageParams, byte[] data) {
try {
String message = new String(data, "UTF-8");
Toast toast = Toast.makeText(getActivity().getApplicationContext(),
message,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
} catch (Exception e) {
}
return true;
}
#Override
public void Mesibo_onMessageStatus(Mesibo.MessageParams messageParams) {
mMessageStatus.setText("Message Status: " + messageParams.getStatus());
}
#Override
public void Mesibo_onActivity(Mesibo.MessageParams messageParams, int i) {
}
#Override
public void Mesibo_onLocation(Mesibo.MessageParams messageParams, Mesibo.Location location) {
}
#Override
public void Mesibo_onFile(Mesibo.MessageParams messageParams, Mesibo.FileInfo fileInfo) {
}
}
Most likely you are creating a token using the wrong App ID
https://mesibo.com/documentation/faq/other/#i-am-not-getting-connection-status-1-online
If you are not getting connection status 1, and getting 4 or 5, you
are not passing the correct appid while creating a token. The appid
passed to create a token must match the Android package name declared
in the AndroidManifest.xml or iOS bundle id declared in the Xcode
project (for example, com.mesibo.xxx ). If you are using Javascript
API or other platforms, ensure that you pass the same app id to the
setAppName API call.
Related
I wanted to ask for your help with something that eating my brain out since I am new at Firebase and android studio. I created this attendance app but only the admin can log into the system then as the admin he has the ability to add students and teachers so that they can have access to the system when they want to log in the system. but once I add a teacher he cannot log in the system. the system saying incorrect username and password while the credentials are all well-typed. is there a way to give access to a user without creating the sign-up page. I am using firebase as the database. here is my code for adding a teacher
public class FacultyAddActivity extends AppCompatActivity {
private Toolbar addFacTool;
private EditText facName, facEmail, facPhone, facID, facAddress;
private Spinner facSpinner;
private String[] designList;
private String selectDesign;
private Button addFacBtn;
private String intentMode, intentFac;
private DatabaseReference facReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_add);
addFacTool = findViewById(R.id.toolAdd);
setSupportActionBar(addFacTool);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
intentFac = intent.getStringExtra("FACULTY");
intentMode = intent.getStringExtra("MODE");
facName = findViewById(R.id.txtLName);
facEmail = findViewById(R.id.txtLEmail);
facAddress = findViewById(R.id.txtLAddress);
facPhone = findViewById(R.id.txtLPhone);
facID = findViewById(R.id.txtLID);
addFacBtn = findViewById(R.id.btnLSubmit);
facSpinner = findViewById(R.id.spnDes);
designList = getResources().getStringArray(R.array.designation);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(FacultyAddActivity.this, android.R.layout.simple_list_item_1, designList);
facSpinner.setAdapter(arrayAdapter);
facSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectDesign = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addFacBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addFaculty();
}
});
}
private void addFaculty() {
String name = facName.getText().toString();
String email = facEmail.getText().toString();
String address = facAddress.getText().toString();
String phone = facPhone.getText().toString();
String ID = facID.getText().toString();
if (name.isEmpty()){
facName.setError("Enter lecturer name");
facName.requestFocus();
}
else if (email.isEmpty()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (address.isEmpty()){
facAddress.setError("Enter lecturer address");
facAddress.requestFocus();
}
else if (phone.isEmpty()){
facPhone.setError("Enter lecturer phone number");
facPhone.requestFocus();
}
else if (selectDesign.isEmpty() && selectDesign.equals("Select Designation")){
Toast.makeText(getApplicationContext(), "Select Designation", Toast.LENGTH_SHORT).show();
}
else if (ID.isEmpty()){
facID.setError("Enter lecturer ID");
facID.requestFocus();
}
else{
facReference = FirebaseDatabase.getInstance().getReference().child("Department").child("Lecturer");
String key = facReference.push().getKey();
FacultyConstructor facultyConstructor = new FacultyConstructor(ID, name, intentFac, selectDesign, phone, email, address, "123456", intentMode);
facReference.child(key).setValue(facultyConstructor).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Lecturer added successfully", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I am developing Android app which obtains information about restaurants from server and shows them in RecyclerView. When first package of information is obtained from server, everything works as expected, but, when I change search criteria and request new package of information from server, RecyclerView becomes blank. I used Toasts to debug what is coming from server and I am convinced that data is properly formatted. Also, variables that are used for accepting the data are also properly handled in code, according to my observations. Do you maybe know why my RecyclerView is empty when second package of data should be shown? Here is the code.
AfterLoginActivity.java
public class AfterLoginActivity extends AppCompatActivity {
/* interface main elements */
LinearLayout afterLoginLayout;
LinearLayout restaurantListLayout;
EditText restaurantEditText;
Button findRestaurantButton;
LoadingDialog loadingDialog;
AlphaAnimation loadingAnimation;
RecyclerView restaurantsRecyclerView;
int recycler_set = 0;
Button signOutButton;
GoogleSignInClient mGoogleSignInClient;
MyAdapter myAdapter = null;
/* server-client communication data */
public static String UploadUrl = "https://gdedakliknem.com/klopator.php";
public static String[] received;
String restaurants[] = new String[40];
String logos_as_strings[] = new String[40];
Bitmap logos[] = new Bitmap[40];
int num_of_elements = 0;
int data_received = 0;
/* user data */
String person_email;
String person_name;
String restaurant;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
/* interface main elements */
afterLoginLayout = findViewById(R.id.afterLoginLayout);
restaurantListLayout = findViewById(R.id.restaurantListLayout);
restaurantEditText = findViewById(R.id.restaurantEditText);
findRestaurantButton = findViewById(R.id.findRestaurantButton);
restaurantsRecyclerView = findViewById(R.id.restaurantsRecyclerView);
signOutButton = findViewById(R.id.signOutButton);
loadingAnimation = new AlphaAnimation(1F, 0.8F);
loadingDialog = new LoadingDialog(AfterLoginActivity.this);
/* UPDATING INTERFACE ELEMENTS */
/* execution thread */
final Handler handler = new Handler();
final int delay = 2000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
/* check if recycler view is set */
if(recycler_set == 0){
/* if not, check if there is data to fil it with */
if(data_received == 1){
/* convert received strings to images */
for(int i = 0; i < num_of_elements; i++){
logos[i] = stringToBitmap(logos_as_strings[i]);
}
/* fill interface elements */
loadingDialog.dismissDialog();
myAdapter = new MyAdapter(AfterLoginActivity.this, restaurants, logos, num_of_elements);
restaurantsRecyclerView.setAdapter(myAdapter);
restaurantsRecyclerView.setLayoutManager(new LinearLayoutManager(AfterLoginActivity.this));
afterLoginLayout.setVisibility(View.GONE);
restaurantListLayout.setVisibility(View.VISIBLE);
recycler_set = 1;
}
}
handler.postDelayed(this, delay);
}
}, delay);
/* catch restaurant name from user's entry */
findRestaurantButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restaurant = restaurantEditText.getText().toString();
if(!restaurant.isEmpty()){
view.startAnimation(loadingAnimation);
loadingDialog.startLoadingDialog();
sendRequest();
} else{
Toast.makeText(AfterLoginActivity.this, "Unesite naziv restorana!", Toast.LENGTH_LONG).show();
}
}
});
/* enable signing out */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.signOutButton:
signOut();
break;
}
}
});
/* obtaining email */
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
person_email = acct.getEmail();
person_name = acct.getDisplayName();
}
}
#Override
public void onBackPressed() {
afterLoginLayout.setVisibility(View.VISIBLE);
restaurantsRecyclerView.setVisibility(View.GONE);
data_received = 0;
recycler_set = 0;
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AfterLoginActivity.this, "Signed out", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if (Response.equals("Restaurant not found")){
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Uneti restoran ne postoji u sistemu! Proverite da li ste dobro napisali naziv", Toast.LENGTH_LONG).show();
} else{
received = Response.split(";");
if (received.length > 0){
data_received = 1;
num_of_elements = received.length / 2;
//Toast.makeText(getApplicationContext(), "num of elements: " + num_of_elements, Toast.LENGTH_LONG).show();
for(int i = 0; i < num_of_elements; i++){
logos_as_strings[i] = received[i*2];
restaurants[i] = received[i*2+1];
//Toast.makeText(getApplicationContext(), "restaurants: " + restaurants, Toast.LENGTH_LONG).show();
}
} else{
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Greška u prijemu", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(final VolleyError error) {
//volleyError = error;
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Toast.makeText(getApplicationContext(), "get params", Toast.LENGTH_LONG).show();
Map<String, String> params = new HashMap<>();
params.put("control", "find_restaurant");
params.put("restaurant", restaurant);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AfterLoginActivity.this);
requestQueue.add(stringRequest);
}
public static Bitmap stringToBitmap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch (Exception e) {
e.getMessage();
return null;
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String restaurants[];
Bitmap logos[];
Context context;
int num_of_elements;
public MyAdapter(Context ct, String rests[], Bitmap lgs[], int num){
context = ct;
restaurants = rests;
logos = lgs;
num_of_elements = num;
Toast.makeText(context, Integer.toString(restaurants.length), Toast.LENGTH_LONG).show();
for(int i = 0; i < restaurants.length; i++){
Toast.makeText(context, restaurants[i], Toast.LENGTH_SHORT).show();
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.restaurant_item_layout, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.restaurantNameTextView.setText(restaurants[position]);
holder.restaurantLogoImageView.setImageBitmap(logos[position]);
holder.restaurantItemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AfterPickingRestaurantActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
logos[position].compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
intent.putExtra("picked_restaurant_name", restaurants[position]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
/*
int i = 0;
if (restaurants != null){
while(restaurants[i] != null){
i++;
}
} else{
i = restaurants.length;
}
return i;
*/
return num_of_elements;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView restaurantNameTextView;
ImageView restaurantLogoImageView;
LinearLayout restaurantItemLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
restaurantNameTextView = itemView.findViewById(R.id.restaurantNameTextView);
restaurantLogoImageView = itemView.findViewById(R.id.restaurantLogoImageView);
restaurantItemLayout = itemView.findViewById(R.id.restaurantItemLayout);
}
}
Add this lines after getting new data
myAdapter.notifyDataSetChanged()
Your Adapter Already set with RecyclerView in OnCreate Method.
so when'er you click on findRestaurantButton you just get Resturent data from server but collected data not pass in adapter so thats why to getting blank adapter..
Just put this line in your onResponse after set data in array..
myAdapter.notifyDataSetChanged()
I found out where is the mistake. If you take a look at the section where overriding of back button click is happening, I by mistake set to GONE recyclerView itself:
restaurantsRecyclerView.setVisibility(View.GONE);
instead of LinearLayout in which recyclerView is contained. Desired action was:
restaurantListLayout.setVisibility(View.GONE);
P.S. Everything works without calling notifyDataSetChanged(), I just create a new instance of myAdapater each time when I receive new data. I hope Garbage Collector is doing its job :)
Thanks everyone on help!
I'm new to Android development and Java in general, so I was wondering if someone could point me in the right direction.
I'm writing a currency convertor app and using Volley requests to send a request to an API to retrieve conversion rates.
Right now I am hardcoding the countries into the URL, which works as the conversion rate is successfully retrieved and displayed. I have two Spinners right now and the goal is to retrieve the string value of the selected Spinner value and then use those values for the json request.
I've created two setOnItemSelectedListeners for both Spinners and set the variable containing the value of the string to that. However, I'm getting an null object reference.
Here is what I have:
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
Double conversionDouble;
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
private Button convertBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnToSpinner();
addListenerOnButton();
jsonSendRequest();
Button convertBtn = (Button) findViewById(R.id.convertBtn);
final EditText fromAmountEditText = findViewById(R.id.fromAmountEditText);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView toAmountTextView = findViewById(R.id.toAmountTextView);
DecimalFormat percentageFormat = new DecimalFormat("0.00");
Double fromAmount = Double.parseDouble(fromAmountEditText.getText().toString());
String result = "$" + percentageFormat.format(conversionDouble*fromAmount);
toAmountTextView.setText(result);
}
});
rq = Volley.newRequestQueue(this);
}
public void jsonSendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
// String url = "http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
String url = "http://free.currencyconverterapi.com/api/v3/convert?q=" + fromSpinnerText + "_" + toSpinnerText + "&compact=ultra";
// Request a string response
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonobject = null;
try {
jsonobject = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonobject.has(fromSpinnerText + "_" + toSpinnerText)) {
try {
conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
// conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void addItemsOnToSpinner(){
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
List<String> currency = new ArrayList<String>();
currency.add("USD");
currency.add("CAD");
currency.add("CNY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, currency
);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(dataAdapter);
fromSpinner.setAdapter(dataAdapter);
fromSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fromSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String toSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void addListenerOnButton() {
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Button convertBtn = (Button) findViewById(R.id.convertBtn);
}
}
Any help is appreciated.
You have declared a few class variables related to your Spinner:
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
You have also correctly defined the onItemSelected() method for the setOnItemSelectedListener.
But, I assume you meant to make the class variables Spinner toSpinnerText, fromSpinnerText; to actually be:
String toSpinnerText = "";
String fromSpinnerText= "";
So that you could call:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fromSpinnerText = (String) parent.getItemAtPosition(position);
}
Notice that the variable fromSpinnerText in the method is now using the class variable instead of the local variable you defined inside the onItemSelected() method.
The same goes for the onItemSelected() method for the other Spinner and toSpinnerText.
I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.
public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return i;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
Map<String, ?> tasks = taskPref.getAll();
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
for(int pos=0 ; pos<myTasks.size() ; pos++){
myTasks.get(pos);
}
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}
And my utlShared class is
public class utlShared {
//context to use later
Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;
public utlShared() {}
public utlShared(Context context)
{
//get context to use it
this.context=context;
//declaretion of shared preferences with file name and file mode (private,public)
userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
//declaration of editor
editor=userPref.edit();
}
//get user and password
public void addUser(String userName, String password)
{
//stores in the phone device under data\data\package name
//put in shared preferences user name and password
editor.putString(userName,password);
//commit (save/apply) the changes.
editor.commit();
}
public boolean checkUser(String userName)
{
//get name by key->userName
String checkString = userPref.getString(userName,"na");
//print to logcat a custom message.....
Log.e("checkUser", "checkUser: "+checkString );
//check if userName equals to responded data, if it's na, we don't have the user...
return !checkString.equals("na");
}
public boolean checkUserPassword(String userName, String userPassword)
{
String checkString = userPref.getString(userName,"na");
return checkString.equals(userPassword);
}
public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
//pointer to user task shared preferences
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
//create editor to change the specific shared preferences
SharedPreferences.Editor taskEditor=taskPref.edit();
//add new task -> if true write 1 else write 0
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
SharedPreferences.Editor tskEditor=taskPref.edit();
tskEditor.clear();
tskEditor.commit();
}
}
This method is called from my Welcome class which is
public class Welcome extends AppCompatActivity {
String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setPointer();
}
private void setPointer()
{
this.context=this;
userName=getIntent().getStringExtra("userName");
myUtl = new utlShared(context);
taskList=(ListView)findViewById(R.id.taskList);
setListData();
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
Button btnBack = (Button)findViewById(R.id.btnBack);
FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
setListData();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void setListData() {
final TaskAdapter adapter = new TaskAdapter(context, userName);
taskList.setAdapter(adapter);
}
public void addCustomTask(View view)
{
//create builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//set title
builder.setTitle("Add new task!");
//inflate view from layout ->custom layout,null,false as defualt values
View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);
final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
String myTaskCustom = txtCustomTask.getText().toString();
String myTaskLine = txtCustomLine.getText().toString();
myUtl.task(userName, myTaskCustom, myTaskLine, false);
setListData();
}
});
//display our inflated view in screen
builder.setView(viewInflated);
//show the dialog
builder.show();
}
}
Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...
Thanks in advance guys, much appreciated!
taskEditor.remove('item tag');
taskEditor.commit();
Guess my question wasnt clear enough but I have found a way to do that.
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
else
{
taskEditor.remove(taskName);
taskEditor.commit();
adapter.notifyDataSetChanged();
}
Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.
Cheers and thanks a lot guys!
I'm creating an app that has an add to cart feature. I follow this tutorial and it works fine, but when i try to add the add to cart in the profile of the product instead in listview, i got an error which is IndexOutOfBoundsException Invalid index 51, size is 0
ProductDetails.java
public class ProductDetails extends Fragment {
static ConnectivityManager cm;
AlertDialog dialog2;
AlertDialog.Builder build;
TextView txtproduct,
txtprice,
txtcategorytype,
txtpieces,
txtdescription;
ImageView imgimage;
Button btncart,
btnview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_details, container, false);
final Controller ct = (Controller) getActivity().getApplicationContext();
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);// checking
build = new AlertDialog.Builder(getActivity()); // connectivity
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions)
.build();
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)// if connection is
// there screen goes
// to next screen
// else shows
// message
.isConnectedOrConnecting()
|| cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting()) {
Log.e("cm value",
""
+ cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting());
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
try {
JSONObject jsonObject1 = new JSONObject(String.valueOf(teaProfileId));
JSONObject jsonObject2 = new JSONObject(teaProfileName);
JSONObject jsonObject3 = new JSONObject(Float.toString(teaProfilePrice));
JSONObject jsonObject4 = new JSONObject(teaProfileImage);
JSONObject jsonObject5 = new JSONObject(teaProfileLabel);
JSONObject jsonObject6 = new JSONObject(String.valueOf(teaProfilePieces));
JSONObject jsonObject7 = new JSONObject(teaProfilePiecesType);
JSONObject jsonObject8 = new JSONObject(teaProfileDescription);
} catch (JSONException e) {
e.printStackTrace();
}
txtproduct = (TextView) rootView.findViewById(R.id.txtproduct);
txtprice = (TextView) rootView.findViewById(R.id.txtprice);
txtcategorytype = (TextView) rootView.findViewById(R.id.txtcategorytype);
txtpieces = (TextView) rootView.findViewById(R.id.txtpieces);
txtdescription = (TextView) rootView.findViewById(R.id.txtdescription);
txtproduct.setText(teaProfileName);
txtprice.setText(("PHP ") + String.format("%.2f", teaProfilePrice));
txtcategorytype.setText(teaProfileLabel);
txtpieces.setText((teaProfilePieces)+" "+(teaProfilePiecesType));
txtdescription.setText(teaProfileDescription.replaceAll("<br />",""));
imgimage = (ImageView)rootView.findViewById(R.id.imgimage);
final ProgressBar progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(teaProfileImage, imgimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
}
else {
build.setMessage("This application requires Internet connection. Would you connect to internet ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
dialog2 = build.create();
dialog2.show();
}
btncart = (Button) rootView.findViewById(R.id.btncart);
btncart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
Toast.makeText(getActivity(), teaProfileName+" was added to cart.", Toast.LENGTH_LONG).show();
ProductModel productsObject = ct.getProducts(teaProfileId);
ct.getCart().setProducts(productsObject);
}
});
btnview = (Button) rootView.findViewById(R.id.btnview);
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getActivity(),Screen1.class);
startActivity(in);
}
});
return rootView;
}
}
Controller.java
public class Controller extends Application {
private ArrayList<ProductModel> myproducts = new ArrayList<ProductModel>();
private ModelCart myCart = new ModelCart();
public ProductModel getProducts(int id){
return myproducts.get(id);
}
public void setProducts(ProductModel products){
myproducts.add(products);
}
public ModelCart getCart(){
return myCart;
}
}
ModelCart.java
public class ModelCart {
private ArrayList<ProductModel> cartItems = new ArrayList<ProductModel>();
public ProductModel getProducts(int position){
return cartItems.get(position);
}
public void setProducts(ProductModel Products){
cartItems.add(Products);
}
public int getCartsize(){
return cartItems.size();
}
public boolean CheckProductInCart(ProductModel aproduct){
return cartItems.contains(aproduct);
}
}
This is the error in logcat.
java.lang.IndexOutOfBoundsException: Invalid index 51, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
.Controller.getProducts(Controller.java:19)
.ProductDetails$4.onClick(ProductDetails.java:192)
This is line 19: return myproducts.get(id);
This is line 192: ProductModel productsObject = ct.getProducts(teaProfileId);