I am trying to extract the value of some particular string values in another class converter.java class from MainActivity.java , but it's cannot be shown. No Logs are shown. Even, if I want to get Data from another class spinnerSelects.java It's also no longer shown in some places. Can You please help me?
MainActivity.java code is here:
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener{
Spinner spinnerMainChoice;
Spinner spinnerInputChoice;
Spinner spinnerOutputChoice;
EditText getInputValueID;
Double inputValue;
TextView outputValueTextViewFromConverter;
Button buttonConvert;
String selectedMainChoice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
/* for input and output fields */
getInputValueID = findViewById(R.id.editTextIDInputValue);
/* ---- Setting Button Properties -----*/
buttonConvert = findViewById(R.id.buttonIDConvert);
buttonConvert.setOnClickListener(this);
/* --- Setting Output TextView field ----*/
outputValueTextViewFromConverter = findViewById(R.id.textViewIDoutputValueToConverter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
selectedMainChoice = parent.getSelectedItem().toString();
Log.i("Selected", selectedMainChoice);
/* Toast.makeText(MainActivity.this, String.valueOf(inputValue), Toast.LENGTH_SHORT).show();*/
/* Implement object of spinnerSelects class*/
spinnerSelects spinnerSelectsInMain = new spinnerSelects(this, spinnerInputChoice, spinnerOutputChoice);
/* the main EVIL '(context) this' in the 2nd parameter, 5 hours wasted, but I learnt many more */
spinnerSelectsInMain.setInputOutputSpinners(selectedMainChoice);
/* calling test for converter class */
/*testOnConverter();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void testOnConverter(){
converter converterInMain = new converter(selectedMainChoice);
}
#Override
public void onClick(View view)
{
String inputValueString = getInputValueID.getText().toString();
inputValue = Double.parseDouble(inputValueString);
/*Toast.makeText(this, String.valueOf(inputValue), Toast.LENGTH_SHORT).show();*/
converter converterInMain = new converter(selectedMainChoice);
double convertedValue = converterInMain.convert(inputValue);
outputValueTextViewFromConverter.setText(String.valueOf(convertedValue));
}
}
converter.java codes here:
package com.gazzali.spinitmeow;
import android.content.Context;
import android.util.Log;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
public class converter {
public String MainChoice, inputChoice, outputChoice;
public converter() {
}
public converter(String selectedMainChoiceFromMain) {
this.MainChoice = selectedMainChoiceFromMain;
/* No Log for Main Choice is Being Shown Here */
Log.i("Main Choice is", MainChoice);
}
public converter(String inputChoiceFromSpinnerSelects, String outputChoiceFromSpinnerSelects){
this.inputChoice = inputChoiceFromSpinnerSelects;
this.outputChoice = outputChoiceFromSpinnerSelects;
/* This Logs Shows But ONLY here */
/* IF I try to show the logs anywhere else in the class, */
/* Either null exception or No Log output */
Log.i("Sub Input Choices are:", inputChoice);
Log.i("Sub Output Choices are:", outputChoice);
}
public double convert(double inputValueForEditTextFieldFromMain)
{
double inputValueInConverter = inputValueForEditTextFieldFromMain;
double outputValueToConverterToMain= 0.00;
/* Here I can't see the Log */
/* Apps Crashes When I press Convert Button*/
Log.i("Sub Input Choices are:", inputChoice);
converterLength converterLengthInConverter = new converterLength();
outputValueToConverterToMain = inputValueInConverter * 22;
/*switch (MainChoice)
{
case "Length":
outputValueToConverterToMain = converterLengthInConverter.convertLength(inputChoice, outputChoice, inputValueInConverter);
break;
}*/
return outputValueToConverterToMain;
}
}
Apps Keeep crashing when I press the convert button.
Locat error shows :
2019-07-21 16:48:33.406 10979-10979/com.gazzali.spinitmeow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gazzali.spinitmeow, PID: 10979
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:166)
at com.gazzali.spinitmeow.converter.convert(converter.java:46)
at com.gazzali.spinitmeow.MainActivity.onClick(MainActivity.java:104)
UPDATE
here's my spinnerSelects class which passes inputChoice and outputChoice parameter to converter class, but still I am geing that weird error.
Although I set the constructor values of converter class by the parameter passed by spinnerSelects , it never sets it values as I can't see inputChoice value inside converter class
package com.gazzali.spinitmeow;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class spinnerSelects implements AdapterView.OnItemSelectedListener{
public String inputChoice, outputChoice;
public Spinner spinnerInputChoice, spinnerOutputChoice;
public ArrayAdapter<CharSequence> adapterInputChoice, adapterOutputChoice;
private Context contextInSpinnerSelects;
public Context getContextInSpinnerSelects() {
return contextInSpinnerSelects;
}
public spinnerSelects() {
/* Empty Constructor */
}
public spinnerSelects(Context contextFromMain, Spinner spinnerInputChoiceFromMain, Spinner spinnerOutputChoiceFromMain) {
this.spinnerInputChoice = spinnerInputChoiceFromMain;
this.spinnerOutputChoice = spinnerOutputChoiceFromMain;
this.contextInSpinnerSelects = contextFromMain;
}
/**
*
* #param selectedMainChoice String retrieves Main Conversion spinner's type
*/
public void setInputOutputSpinners(String selectedMainChoice) {
switch (selectedMainChoice)
{
case "Length": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.LengthChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.LengthChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
case "Temperature": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.TemperatureChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.TemperatureChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
case "Weight": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.WeightChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.WeightChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
}
}
private void setInputOutputListenerAndDropDownAndAdapter() {
spinnerInputChoice.setOnItemSelectedListener(this);
spinnerOutputChoice.setOnItemSelectedListener(this);
adapterInputChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerInputChoice.setAdapter(adapterInputChoice);
adapterOutputChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOutputChoice.setAdapter(adapterOutputChoice);
}
public Spinner getSpinnerInputChoice() {
return spinnerInputChoice;
}
public Spinner getSpinnerOutputChoice() {
return spinnerOutputChoice;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
inputChoice = spinnerInputChoice.getSelectedItem().toString();
outputChoice = spinnerOutputChoice.getSelectedItem().toString();
converter converterInSpinnerSelects = new converter(inputChoice, outputChoice);
/*converterInSpinnerSelects.setInputOutputChoice(inputChoice, outputChoice);*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Your problem might be that inputChoice is never set.
You are creating a new instance of your converter-class with this code:
converter converterInMain = new converter(selectedMainChoice);
this will ONLY run this code in your converter-instance:
public converter(String selectedMainChoiceFromMain) {
this.MainChoice = selectedMainChoiceFromMain;
/* No Log for Main Choice is Being Shown Here */
Log.i("Main Choice is", MainChoice);
}
the second constructor therefore never executes public converter(String inputChoiceFromSpinnerSelects, String outputChoiceFromSpinnerSelects){ what means that you never set inputChoicenor outputChoice in your converter-instance which means that they stay null
Log.i("Sub Input Choices are:", inputChoice); therefore gets a null as inputChoice
But I don't think this is the problem here. It should still work but just output a null into your console. As I remember Log.i() works like this: Log.i(TAG, MESSAGE) so your code should look something like this:
Log.i("CONVERTER", "Sub Input Choices are: " + inputChoice);
UPDATE
Well now you are creating a new instance of convertor in (AdapterView<?> parent, View view, int position, long id) {
converter converterInSpinnerSelects = new converter(inputChoice, outputChoice);
this will NOT update the values of the convertor-instance you create in your onClick(View view)-function.
One way of solving this problem might be to simply put the Strings static:
public static String MainChoice, inputChoice, outputChoice;
But then there is no need for creating a new instance of converter every time... so simply do this then:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
converter.inputChoice = spinnerInputChoice.getSelectedItem().toString();
converter.outputChoice = spinnerOutputChoice.getSelectedItem().toString();
}
Related
I have a RecyclerView but I face some problems. Whenever I add something to the recycler view and for example switch fragments or close the app all the items in the RecyclerView disappear. Would there be a way to save them? Any help would be nice!
Here is some code to see if anyone needs it:
Adapter
package com.example.freetrialtracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class SubTrialAdapter extends RecyclerView.Adapter<SubTrialAdapter.MyViewHolder>{
private ArrayList<SubTrial> listData;
private Context context;
private OnEditListener onEditListener;
public SubTrialAdapter(Context context, ArrayList<SubTrial> list,OnEditListener onEditListener){
this.listData=list;
this.context=context;
this.onEditListener=onEditListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View viewItem= LayoutInflater.from(parent.getContext()).inflate(R.layout.subscription_card_view,parent,false);
return new MyViewHolder(viewItem);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
SubTrial dataObj=listData.get(position);
holder.nameTxt.setText(dataObj.getNamee());
holder.startDate.setText(dataObj.getStartDate());
holder.endDate.setText(dataObj.getEndDate());
holder.description.setText(dataObj.getDescription());
holder.link.setText(dataObj.getLink());
holder.imgDelete.setOnClickListener(v->{
listData.remove(position);
notifyDataSetChanged();
});
holder.imgEdit.setOnClickListener(v->{
onEditListener.onEditClick(listData.get(position),position);
});
}
#Override
public int getItemCount() {
return listData.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView nameTxt,startDate,endDate,description,link;
ImageView imgEdit,imgDelete;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
nameTxt=itemView.findViewById(R.id.nameTxtId);
startDate=itemView.findViewById(R.id.startDateTxtId);
endDate = itemView.findViewById(R.id.endDateTxtId);
description = itemView.findViewById(R.id.descriptionId);
link = itemView.findViewById(R.id.linkId);
imgEdit=itemView.findViewById(R.id.imgEdit);
imgDelete=itemView.findViewById(R.id.imgDelete);
}
}
public void editData(SubTrial listDataObj,int currentPosition){
listData.get(currentPosition).setLink(listDataObj.getLink());
listData.get(currentPosition).setDescription(listDataObj.getDescription());
listData.get(currentPosition).setEndDate(listDataObj.getEndDate());
listData.get(currentPosition).setStartDate(listDataObj.getStartDate());
listData.get(currentPosition).setNamee(listDataObj.getNamee());
notifyDataSetChanged();
}
public interface OnEditListener{
void onEditClick(SubTrial listCurrentData, int CurrentPosition);
}
}
Fragment
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class SubscriptionFragment extends Fragment implements SubscriptionDialogFragment.OnInputSelected {
AlertDialog alertDialog;
TextView textView1;
RecyclerView subscriptionList;
private FloatingActionButton mOpenDialog;
SubTrialAdapter subscriptionAdapterList;
ArrayList<SubTrial> subTrialArrayList;
#Override
public void sendInput(String name, String startDate, String endDate, String description, String link) {
addSubscription(name, startDate, endDate, description, link);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subscription, container, false);
mOpenDialog = view.findViewById(R.id.fabSub);
subTrialArrayList = new ArrayList<>();
subscriptionList = view.findViewById(R.id.activityListSub);
subscriptionList.setHasFixedSize(true);
subscriptionList.setLayoutManager(new LinearLayoutManager(this.getActivity(), LinearLayoutManager.VERTICAL, false));
textView1 = view.findViewById(R.id.textView1);
mOpenDialog.setOnClickListener(v -> {
SubscriptionDialogFragment dialog = new SubscriptionDialogFragment();
dialog.setTargetFragment(SubscriptionFragment.this, 1);
dialog.show(getFragmentManager(), "Dialog");
});
return view;
}
public void addSubscription(String strName, String strStartDate, String strEndDate, String strDescription, String strLink) {
textView1.setText(strStartDate);
SubTrial obj = new SubTrial();
obj.setNamee(strName);
obj.setStartDate(strStartDate);
obj.setEndDate(strEndDate);
obj.setDescription(strDescription);
obj.setLink(strLink);
subTrialArrayList.add(obj);
subscriptionAdapterList = new SubTrialAdapter(this.getContext(), subTrialArrayList, this::onEditClick);
subscriptionList.setAdapter(subscriptionAdapterList);
}
private void onEditClick(SubTrial listCurrentData, int currentPosition) {
View view=LayoutInflater.from(this.getContext()).inflate(R.layout.edit_subscription,null);
AlertDialog.Builder builderObj=new AlertDialog.Builder(view.getContext());
EditText mSubscriptionName = view.findViewById(R.id.subscriptionName);
EditText mStartDate = view.findViewById(R.id.startDate);
EditText mEndDate = view.findViewById(R.id.endDate);
EditText mDescription = view.findViewById(R.id.description);
EditText mLink = view.findViewById(R.id.link);
MaterialButton btnEdit=view.findViewById(R.id.btnEdit);
mSubscriptionName.setText(listCurrentData.getNamee());
mStartDate.setText(listCurrentData.getStartDate());
mEndDate.setText(listCurrentData.getEndDate());
mDescription.setText(listCurrentData.getDescription());
mLink.setText(listCurrentData.getLink());
ImageView closeAlert = view.findViewById(R.id.closeAlert);
builderObj.setView(view);
builderObj.setCancelable(false);
closeAlert.setOnClickListener(v -> {
alertDialog.cancel();
});
btnEdit.setOnClickListener(v->{
String strName = "", strStartDate = "", strEndDate = "", strDescription = "", strLink = "";
if (mSubscriptionName.getText() != null) {
strName = mSubscriptionName.getText().toString();
}
if (strName.equals("")) {
Toast.makeText(this.getContext(), "Please enter Subscription Name", Toast.LENGTH_LONG).show();
return;
}
if (mStartDate.getText() != null) {
strStartDate = mStartDate.getText().toString();
}
if (strStartDate.equals("")) {
Toast.makeText(this.getContext(), "Please enter Start Date", Toast.LENGTH_LONG).show();
return;
}
if (mEndDate.getText() != null) {
strEndDate = mEndDate.getText().toString();
}
if (strEndDate.equals("")) {
Toast.makeText(this.getContext(), "Please enter End Date", Toast.LENGTH_LONG).show();
return;
}
if (mDescription.getText() != null) {
strDescription= mDescription.getText().toString();
}
if (strDescription.equals("")) {
Toast.makeText(this.getContext(), "Please enter Description", Toast.LENGTH_LONG).show();
return;
}
if (mLink.getText() != null) {
strLink = mLink.getText().toString();
}
if (strLink.equals("")) {
Toast.makeText(this.getContext(), "Please enter Link", Toast.LENGTH_LONG).show();
return;
}
editContact(strName, strStartDate, strEndDate, strDescription, strLink, currentPosition);
});
alertDialog=builderObj.create();
alertDialog.show();
}
public void editContact(String strUserName, String strStartDate, String strEndDate, String strDescription, String strLink, int currentPosition){
SubTrial obj = new SubTrial();
obj.setNamee(strUserName);
obj.setStartDate(strStartDate);
obj.setEndDate(strEndDate);
obj.setDescription(strDescription);
obj.setLink(strLink);
subscriptionAdapterList.editData(obj,currentPosition);
alertDialog.cancel();
}
}
Yes. Because once you exit the Application, the app memory is killed in the background process and opening up the app creates a new instance. Let's say for example, you created an editText and button which displays a Toast + text entered by the user to the user when clicked. The app memory will stop once you close and it will shutdown once you remove it from background memory. This method is called onDestroy().
So to prevent this, you can make use of android default local storages e.g
SQlite Database, Shared Preferences, Room Database
1. Sqlite database is android's offline local database which requires no internet access to store data. And data to be stored in SQlite Database should be in strings format like uri path. Storing bigger files or contents like images, audios, videos inside the SQLite database is not advisible to prevent exceptions such as;
FATAL EXCEPTION: main
11-06 15:16:17.199: E/AndroidRuntime(1789): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.demodbimage/com.example.demodbimage.ImagesList}: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
2. Shared Preferences is good for storing very small data values in form of keys such as strings, boolean, integers. Take for instance, you want to prevent user from logging in after first time login is successful or you want to display dark theme next time once the user opt-in the first time.
3. Room Database is same as Sqlite database but Google recommends us to use it because it's easy to use, also provides databases syntax and very sensitive to errors.
Or you can make use of Online databases eg mySQL, MongoDB, Firebase Database, mariaDb etc.
Basically, RecyclerView is used in conjunction with the database like Room(Local DB) or API(Remote DB such as MySQL).
However, if you are creating a very lightweight project for your portfolio, I don't think it's a bad idea to use a datastore or sharedPrefereces. As with any program, List and Array commonly used in Kotlin are, of course, volatile.
I'm pretty new to Android Studio and Java overall so this might be simple question but I couldn't find any solutions or either couldn't use them to fix my issue.
So I have a RecyclerView which I can insert items from a list of pre-defined items with the function "addItems()" when I press to a button and display them.
Also those items have ImageButtons -which is just a transparent rectangle- to get individual clicks on them.
The purpose of these ImageButtons are to switch to a new activity which I defined in the "addItems()" method.
But the problem is, I can't catch -but they respond to the clicks- click on those items, and also I can't pass the activity class or the layout file.
To be exact, I want to use these buttons to switch to a new activity and display the info of that item there.
It's my first question here, so if I need to show any code, please tell me to.
NewsAdapter.java
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder>
{
Context mContext;
List<NewsItem> mData;
public NewsAdapter(Context mContext, List<NewsItem> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View layout;
layout = LayoutInflater.from(mContext).inflate(R.layout.lyt_restoran,viewGroup,false);
return new NewsViewHolder(layout);
}
// Changed below ----------
#Override
public void onBindViewHolder(#NonNull NewsViewHolder newsViewHolder, int position) {
// Bind data here
newsViewHolder.tvSellerName.setText(mData.get(position).getSellerName());
newsViewHolder.tvSellerAddress.setText(mData.get(position).getSellerAddress());
newsViewHolder.ivSellerImage.setImageResource(mData.get(position).getSellerImage());
newsViewHolder.tvMinCost.setText(mData.get(position).getMinCost());
newsViewHolder.tvMinTime.setText(mData.get(position).getMinTime());
newsViewHolder.tvDeliveryCost.setText(mData.get(position).getDeliveryCost());
newsViewHolder.tvClassToGo.setText(mData.get(position).getClassToGo());
// Line below is the buttons attached to the items which I aim to use on switching Activities
newsViewHolder.ibGoSellerPage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(SiparisActivity.this, classDominos.class);
startActivity(intent); // startActivity is marked red
}
});
}
// Changed above ----------
#Override
public int getItemCount() {
return mData.size();
}
public class NewsViewHolder extends RecyclerView.ViewHolder{
TextView tvSellerName, tvSellerAddress, tvMinCost, tvMinTime, tvDeliveryCost, tvClassToGo;
ImageView ivSellerImage;
ImageButton ibGoSellerPage;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
tvSellerName = itemView.findViewById(R.id.tvFoodName);
tvSellerAddress = itemView.findViewById(R.id.tvFoodDescription);
ivSellerImage = itemView.findViewById(R.id.ivFoodImage);
tvMinCost = itemView.findViewById(R.id.tvFoodCost);
tvMinTime = itemView.findViewById(R.id.tvMinTime);
tvDeliveryCost = itemView.findViewById(R.id.tvDeliveryCost);
tvClassToGo = itemView.findViewById(R.id.tvClassToGo);
ibGoSellerPage = itemView.findViewById(R.id.ibGoSellerPage);
//int position = getAdapterPosition();
//Toast.makeText(mContext.getApplicationContext(), "Position is: "+position, Toast.LENGTH_SHORT).show();
}
}
}
SiparisActivity.java //this is where I list restaurant items with ImageButtons said above.
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import recyclerview.CustomItemAnimator;
public class SiparisActivity extends AppCompatActivity {
Button btnListRestaurants;
RecyclerView NewsRecyclerView;
NewsAdapter newsAdapter;
List<NewsItem> mData;
ImageButton ibGoSellerPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_siparis);
// Hide the action bar
getSupportActionBar().hide();
NewsRecyclerView = findViewById(R.id.news_rv);
btnListRestaurants = (Button) findViewById(R.id.buttonListRestaurants);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
NewsRecyclerView.setHasFixedSize(true);
NewsRecyclerView.setItemAnimator(new CustomItemAnimator());
// Get clicks on the "List Restaurants"
btnListRestaurants.setOnClickListener(new View.OnClickListener() {
int restaurantCount = 0;
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getApplicationContext(), "Listing Restaurants", Toast.LENGTH_SHORT);
toast.show();
Timer timerToTransition;
timerToTransition = new Timer();
TimerTask task = new TimerTask() {
public void run() {
addItems();
restaurantCount++;
if (restaurantCount > 9)
{
System.out.println(restaurantCount);
timerToTransition.cancel(); // Stops the timer when theres 10 Restaurants listed
}
}
};
timerToTransition.scheduleAtFixedRate(task,0,300); // waits 300ms before creating a new Restaurant
}
});
if (ibGoSellerPage != null) // Check if Restaurant button exists
{
System.out.println("ON CLICK HERE");
ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
}
mData = new ArrayList<>();
// fill list news with pre defined data
// Adapter ini and setup
newsAdapter = new NewsAdapter(this,mData);
NewsRecyclerView.setAdapter(newsAdapter);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void addItems()
{
RecyclerView.State state = null;
int switchInt = 0; // To use in the switch
// Random integer list to assign switchInt a random value
int[] intList;
intList = new int[]{0,1,2,3,4,5,6,7};
// Pick a random int
Random rand = new Random();
int rndInt = rand.nextInt(5);
// Check if the array's index isn't empty(-1)
while (intList[rndInt] != -1)
{
switchInt = (int) intList[rndInt];
intList[rndInt] = -1;
}
//System.out.println(rndInt);
switch(switchInt) {
case 0:
mData.add(0,new NewsItem("Domino's Pizza","Sarıgöl, Ordu Cd. No:128, 34240 Gaziosmanpaşa/İstanbul",
R.drawable.dominos,"32 TL","30 dk.","0 TL","classDominos")); // I'm trying to catch that "classDominos" to use to switch Activity
break;
case 1:
mData.add(0,new NewsItem("Migros","Bağlarbaşı, Küçükköy Yolu Cd., 34245 Gaziosmanpaşa/İstanbul",
R.drawable.migroslogo,"32 TL","25 dk.","0 TL", "classDominos"));
break;
case 2:
mData.add(0,new NewsItem("KFC","Yeşilpınar Mah. Şehit Metinkaya Sok Vialand AVM No:11 Mağaza No:237, 34065 Eyüpsultan",
R.drawable.kfclogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 3:
mData.add(0,new NewsItem("Popeyes","Yeşilpınar Mah. Şehit Metin Kaya Sok. No:11 K:3 Vialand AVM, 34065",
R.drawable.popeyeslogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 4:
mData.add(0,new NewsItem("Mado","İslambey, Hz. Halid Blv. No:43 D:B, 34050 Eyüpsultan/İstanbul",
R.drawable.madologo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
default:
break;
}
System.out.println("Added item");
newsAdapter.notifyItemInserted(0);
NewsRecyclerView.getLayoutManager().smoothScrollToPosition(NewsRecyclerView, state, 0);
// Un-commenting the lines below crash the app when "Listing Restaurants" (Creating items)
//ibGoSellerPage = (ImageButton) findViewById(R.id.ibGoSellerPage);
/*ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
*/
}
}
I can see the individual buttons in the profiler but how to catch clicks on them? (You can see I'm holding the button on the right)
Profiler Screenshot
I think the problem with you is that the click event happen on the screen in another view
By making a transparent rectangle i think the click go to the parent view
Try to test that for ex:
<LinearLayout
android:id="#+id/layout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
handle the click on layout view if it work so you need to change the transparent rectangle button to a bold one or another approach
better to add some code from your side to help us understand the problem well
I'm working on an Android app so I can learn mobile dev and I'm stuck with this problem.
Basically in my SampleFragment class I have an adapter called mAdapter and when my TestService gets my data objects and updates my dataObjects arrayList and notifies the adapter that the data has changed the adapter isn't initialized and is null at the time. Is it a thread issue or is it associated with the fragment lifecycle?
SampleFragment.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class SampleFragment extends Fragment {
private static final int SEND_DELAY = 1500;
private String userName, sEventId;
private EditText etMessage;
private ImageButton btSend;
private Context applicationContext;
private View view;
private Handler handler = new Handler();
private ArrayList<Message> dataObjects = new ArrayList<>();
private MessageListAdapter mAdapter;
private Runnable initMessageAdapter = new Runnable() {
#Override
public void run() {
initMessageAdapter();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String eventName = CurrentActiveEvent.getInstance().getEventName();
Activity activity = getActivity();
activity.setTitle(eventName);
mAdapter = new MessageListAdapter(context, userName, dataObjects);
CurrentActiveUser currentUser = CurrentActiveUser.getInstance();
userName = currentUser.getUsername();
Intent intent = new Intent(activity, TestService.class);
activity.startService(intent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_messaging, container, false);
applicationContext = getActivity();
sEventId = CurrentActiveEvent.getInstance().getEventID();
btSend = (ImageButton) view.findViewById(R.id.btSend);
handler.post(initMessageAdapter);
btSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(new Runnable() {
#Override
public void run() {
saveMessage(body);
}
});
}
});
return view;
}
// Setup message field and posting
private void initMessageAdapter() {
etMessage = (EditText) view.findViewById(R.id.etMessage);
ListView lvChat = (ListView) view.findViewById(R.id.lvChat);
lvChat.setAdapter(mAdapter);
}
public void updatedataObjects(List<objs> newdataObjects){
this.dataObjects.clear();
this.dataObjects.addAll(newdataObjects);
mAdapter.notifyDataSetChanged();
}
}
TestService.java
import android.app.IntentService;
import android.content.Intent;
import java.util.Collections;
import java.util.List;
public class TestService extends IntentService {
private static final int MAX_RESULTS = 50;
private static final String CLASS_NAME = TestService.class.getSimpleName();
private final String sEventId = CurrentActiveEvent.getInstance().getEventID();
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public TestService() {
super(CLASS_NAME);
}
#Override
#SuppressWarnings("unchecked")
protected void onHandleIntent(Intent intent) {
if (NetworkState.isConnected(getApplicationContext())) {
Query query = new Query(Data.class);
query.whereEqualTo(Events.ID, sEventId);
query.orderByDESC(Data.CREATED_AT);
query.setLimit(MAX_RESULTS);
List objs = queryDB(query, Data.class.getSimpleName());
if (objs != null) {
Collections.reverse(objs);
new SampleFragment().updateMessages(objs);
}
}
}
}
Your problem comes from this line:
new SampleFragment().updateMessages(objs);
You are creating a new instance of your fragment inside your service. Since you are not attaching the fragment anywhere, it's lifecycle is not started and the onCreate() method is never called, which results in the NullPointerException.
IntentServices are great for executing tasks on a background thread, but they are components, that are meant to be separated from the UI - related components, like Activities and Fragments. You should never have direct communication between an IntentService and a Fragment or Activity. If you need to return a result from your IntentService, you should consider using the LocalBroadcastManager. It will fire an intent, containing the result, and you can register receivers to intercept it.
There are also other options, like Bound Services - they are created to provide an interface for their clients, and you can use this to return your result. But bear in mind, that, unlike IntentService they don't work in a background thread by default.
Since you are trying to work with a database, I recommend you take a look and the ContentProvider and ContentResolver classes. They are the recommended way of working with DBs in Android and come with loads of neat stuff.
I am using a simple spinner to display buy-in values in an integer-array. The error in the Gradle Build says: method getOnItemSelectedListener in class AdapterView<T> cannot be applied to given types. There are no required arguments and the reason for the error is given as: actual and formal arguments lists differ in length where T is a type-variable: T extends Adapter declared in class AdapterView. I am not sure how to resolve the error which appears on (this):
spinner.getOnItemSelectedListener(this);
I would assume that this is correct practice as I am telling the spinner that this activity is responsible for listening to the events on the spinner.
Here is my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AdapterView.OnItemSelectedListener{
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the view from home_activity.xml
setContentView(R.layout.home_activity);
// initialize spinner
spinner = (Spinner) findViewById(R.id.buyInSpinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.buy_in, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.getOnItemSelectedListener(this);
} // end onCreate method
#Override
public void onItemSelected(AdapterView<?> adapterView, View v, int i, long l)
{
TextView myText = (TextView) v;
Toast.makeText(this, "You Selected "+myText.getText(), Toast.LENGTH_SHORT).show();
} // end onItemSelected method
#Override
public void onNothingSelected(AdapterView<?> adapterView)
{
Toast.makeText(this, "You Must Buy-In To Play", Toast.LENGTH_SHORT).show();
} // end onNothingSelected method
} // end HomeActivity class
Why do you want to get without a variable?
I think in this case you should use spinner.setOnItemSelectedListener(this); instead
I have a MainClass which one is the full app, when I click one button I go to another class (PopupValores) which one I make it looks like a popup. In this class I have a EditText where you type a integer and a button to close this class. My question is how to get that int typed in PopupClass and use it in MainClass. Heres the code for the PopupValores.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PopupValores extends Activity implements OnClickListener {
TextView texto;
String mensaje;
EditText editable;
Button ok;
public static int cantidad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupvalores);
ok = (Button) findViewById (R.id.Bok);
texto = (TextView) findViewById (R.id.textView1);
editable = (EditText) findViewById (R.id.editText1);
mensaje = editable.getText().toString();
ok.setOnClickListener(this);
ok.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View arg0) {
finish();
return true;
}
});
}
public void onClick(View v){
switch(v.getId()){
case R.id.Bok:
String mensaje;
mensaje = editable.getText().toString();
cantidad = Integer.parseInt(mensaje);
texto.setText("New value " + cantidad + ".");
}
}
}
Then in my MainClass I click a button and it shows the int
int id, vaas = PopupValores.cantidad;
public void onClick (View v)
{
posicion = (ImageCell) v;
seleccion = posicion.mCellNumber;
if (seleccion == -1){
....
toast (id + " " + vaas);
....
}
}
But instead of showing the value declared in PopupValores it shows 0. What I'm doing wrong here?
You need to call the popup Activity with Activity.startActivityForResult()
Once finishing the popup Activity, set the requested result via Activity.setResult() (you can save your data in the intent's bundle)
In your main Activity, override onActivityResult and retrieve the data
Its called startActivityforResult
and has been answered soo many times here on stackoverflow Here is one