How to use an `Arraylist` in `OnClick` method? - java

When I try to use an ArrayList, and StringBuffer in OnClick method, Android studio wants me to change them to final. But when I do that, I can only keep the last inserted element in ArrayList.
SharedPreferences sp = mContext.getSharedPreferences("checked",Context.MODE_PRIVATE);
final SharedPreferences.Editor e=sp.edit();
final ArrayList<Integer> sharedP= new ArrayList<>();
final String word = words.get(position).getMean();
final int id= words.get(position).getId();
final StringBuffer str= new StringBuffer("");
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
sharedP.remove(sharedP.indexOf(id));
holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
sharedP.add(id);
holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}
for(int i=0;i<sharedP.size();i++){
Log.e("sharedpreference1",sharedP.get(i).toString());
str.append(sharedP.get(i));
}
e.putString("str", str.toString());
e.commit();
}
});
Updated code
SharedPreferences sp = mContext.getSharedPreferences("checked",Context.MODE_PRIVATE);
e=sp.edit();
sharedP= new ArrayList<>();
word = words.get(position).getMean();
Log.e("getMean",word);
id= words.get(position).getId();
str= new StringBuffer("");
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
sharedP.remove(sharedP.indexOf(word));
flag=false;
holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
sharedP.add(word);
flag=true;
Log.e("deneme",word);
holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}
str.delete(0,str.length());
for(int i=0;i<sharedP.size();i++){
Log.e("sharedpreference1",sharedP.get(i).toString());
str.append(sharedP.get(i));
str.append(".");
}
if(flag==false){
e.remove("str");
e.commit();
}
Log.e("size",str.toString());
e.putString("str", str.toString());
e.remove("set");
e.commit();
}
});
but it still returns the last element of Array
example of checkedTextView
shared preference

You have to declare your variables outside of that method.
private SharedPreferences.Editor e;
private ArrayList<Integer> sharedP= new ArrayList<>();
private String word = null;
private int id= 0;
private StringBuffer str = null;
Then:
e=sp.edit();
sharedP= new ArrayList<>();
word = words.get(position).getMean();
id= words.get(position).getId();
str= new StringBuffer("");

Declare the Arraylist and the String Buffer as global variables.
private ArrayList<Integer> sharedP = new ArrayList<>();
private StringBuffer str = new StringBuffer("");

Related

How can I make the LiveData getValue() function return the list of items from my rooms database in Android?

I have a getAllFlights() method in my ViewModel class which is supposed to return all the flights in my rooms database, however, when I call the method in my activity, it returns null even though I have flights existing in the database. Below is the code for my activity where I am calling flightViewModel.getAllFlights.getValue() method. I am using the MVVM model.
Activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_listing);
uploadAllBtn = findViewById(R.id.uploadAllReports);
searchFlights = findViewById(R.id.searchFlightText);
mRecyclerView = findViewById(R.id.recyclerView);
flightViewModel = new ViewModelProvider(this).get(FlightViewModel.class);
flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
#Override
public void onChanged(List<Flight> flight_list) {
String flightno = flight_list.get(1).getFlightNumber();
String flightdate = flight_list.get(1).getDate();
String[] flight_details = new String[2];
flight_details[0]= flightno;
flight_details[1] = flightdate;
Log.v("pp", flight_details[0]);
for(int i = 0; i <flight_list.size();i++){
String flightnumber = flight_list.get(i).getFlightNumber();
String departuredate = flight_list.get(i).getDate();
reportitems.add(new ReportItem(flightnumber,departuredate));
}
flightViewModel.getAllFlights().removeObservers(ReportListingActivity.this);
}
});
mLayoutManager = new LinearLayoutManager(ReportListingActivity.this);
mAdapter = new ReportAdapter(reportitems, ReportListingActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
you should not use getValue() in case of observing the data you should use observe() method of your livedata.
update:
you can use this code:
flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
#Override
public void onChanged(List<Flight> flight_list) {
if (flight_list.size() == 0) return;
String flightno = flight_list.get(0).getFlightNumber();
String flightdate = flight_list.get(0).getDate();
String[] flight_details = new String[2];
flight_details[0]= flightno;
flight_details[1] = flightdate;
for(int i = 0; i <flight_list.size();i++){
String flightnumber = flight_list.get(i).getFlightNumber();
String departuredate = flight_list.get(i).getDate();
reportitems.add(new ReportItem(flightnumber,departuredate));
}
mRecyclerView.getAdapter().notifyDataSetChanged()
flightViewModel.getAllFlights().removeObservers(this);
}
});

How to get child class objects from array list?

I am having trouble getting the earlier class objects of an array list in the 'onPostExecute' method of my asynch class. To simplify things for this post, I'm just trying to set the text of the 'name' to my textview in my onPostExecute method like so.
myTextView.setText(VideoDetail_List.get(0).getVideoName());
However the problem is that the String that is returning is the last instance of the videoname object in the string array, instead of the first instance of the video name, which should be the child class object of the VideoDetail_List at the 0 index.
AsyncTask Class
final JSONObject obj = new JSONObject(result);
final JSONArray videoData = obj.getJSONArray("data");
final int n = videoData.length();
for (int i = 0; i < n; ++i) {
final JSONObject video = videoData.getJSONObject(i);
videoDetail.setVideoName(video.getString("name"));
videoDetail.setVideoDuration(video.getString("duration"));
final JSONObject videoPictures = video.getJSONObject("pictures");
final JSONArray videoPictureSizes = videoPictures.getJSONArray("sizes");
final JSONObject videoPictureLink = videoPictureSizes.getJSONObject(1);
videoDetail.setPictureLink(videoPictureLink.getString("link"));
//pictureLink.add(videoPictureLink.getString("link"));
final JSONArray videoURLTypes = video.getJSONArray("download");
final JSONObject videoURLLink = videoURLTypes.getJSONObject(0);
videoDetail.setVideoLink(videoURLLink.getString("link"));
//videoLink.add(videoURLLink.getString("link"));
VideoDetail_List.add(i,videoDetail);
}
return VideoDetail_List;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(List<VideoDetail> VideoDetail_List) {
System.out.println("RESPONSE: " + VideoDetail_List);
final TextView myTextView = new TextView(mContext);
myTextView.setText(VideoDetail_List.get(0).getVideoName());
mLayout.addView(myTextView);
myTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sText = myTextView.getText().toString();
//Toast toast = Toast.makeText(this, sText, Toast.LENGTH_SHORT);
Toast toast = Toast.makeText(mContext, sText, Toast.LENGTH_LONG);
toast.show();
}
});
}
VideoDetail Class
public class VideoDetail {
private String videoName;
private String videoDuration;
private String pictureLink;
private String videoLink;
public String getVideoName() {
return this.videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public String getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(String videoDuration) {
this.videoDuration = videoDuration;
}
public String getPictureLink() {
return pictureLink;
}
public void setPictureLink(String pictureLink) {
this.pictureLink = pictureLink;
}
public void setVideoLink(String videoLink){
this.videoLink = videoLink;
}
public String getVideoLink() {
return videoLink;
}
}
Thank you in advance for your help!
However the problem is that the String that is returning is the last
instance of the videoname object in the string array
That's because you are overriding the content of the only instance of VideoDetails at every iteration of your for loop. You should instantiate it at every iteration
for (int i = 0; i < n; ++i) {
videoDetail = new VideoDetail();

How to store received data in an array?

I am working on an Android application which receives data from an RFDuino and displays it on a Line Chart.
In my Mainactivity, the broadcastReceiver sends data into a method addData on receiving.
private final BroadcastReceiver rfduinoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (RFduinoService.ACTION_CONNECTED.equals(action)) {
upgradeState(STATE_CONNECTED);
} else if (RFduinoService.ACTION_DISCONNECTED.equals(action)) {
downgradeState(STATE_DISCONNECTED);
} else if (RFduinoService.ACTION_DATA_AVAILABLE.equals(action)) {
addData(intent.getByteArrayExtra(RFduinoService.EXTRA_DATA));
}
}
};
The addData method is as follows:
public void addData(byte[] data) {
View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, dataLayout, false);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
String riz = HexAsciiHelper.bytesToHex(data);
t1 = Integer.parseInt(riz, 16);
String testString = String.valueOf(t1);
text1.setText(testString);
dataLayout.addView(view,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
}
Now, I want to store value of t1 into an array. The problem is that when I try to do it, a NullPointerException occurs and the program stops.
Any help would be appreciated.
Declare ArrayList<Integer> and Store the t1 value after doing null check.
ArrayList <Integer> t1array = new ArrayList <Integer> ();
String riz = HexAsciiHelper.bytesToHex(data);
if (riz != null) {
Integer t1 = t1 = Integer.parseInt(riz, 16);
t1array.Add(t1);
}

Android: compare string input (edittext) with arraylist

I want to compare my input string with an array list of another class, so I used the searchfield to compare them. As below it works fine.
Input Class
public class Suche extends Activity{
private Button zumergebnis;
final Intent zum_ergebnis = new Intent("android.intent.action.activity_ergebnis");
static String mystring;
static void setstring(String textView){
mystring = textView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suche);
zumergebnis = (Button) findViewById(R.id.zumergebnis);
zumergebnis.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
EditText searchinput = (EditText) findViewById(R.id.editText1);
String from = searchinput.getText().toString();
setstring(from);
startActivity(zum_ergebnis);
}
});}
}
Comparing Class
public class Ergebnis extends Suche
{
private TextView textView;
static String getstring(){
return mystring;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ergebnis);
textView = (TextView) findViewById(R.id.textView2);
textView.setText(mystring);
class2 Object = new class2();
final ArrayList<String> word = Object.method2();
ListAdapter listenAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, word);
ListView mystringsView = (ListView) findViewById(R.id.listView1);
mystringsView.setAdapter(listenAdapter);
textView = (TextView) findViewById(R.id.textView2);
String searchField = (mystring);
for (String s : word)
{
if (searchField.toString().contains(s))
{
textView.setText("Your word"+mystring+"exists in the list");
}
else
{
textView.setText("Word"+mystring+"doesnt exist");
continue;
}
break;
}
}
}
list class
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno");
word.add("dos");
word.add("tres");
return word;
}
}
but when adding a second:
list class
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno; one");
word.add("dos; two");
word.add("tres; three");
return word;
}
}
'column' the app stops.
Anyone an idea how to even search for the second entry?
For everyone who is interested in the solution for that problem, the for- loop has to be changed to:
for (int i = 0; i < word.size(); i++) {
if (word.get(i).contains(searchField.trim())) {
textView.setText("Your input '" +mystring+ "' exists.");
}
else
adding some entries to the arraylist:
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno; one");
word.add("dos; two");
return word;
}
it works fine now.

removing words from a string in java

Could anyone tell me what is wrong in my code?
I am trying to pass a string to function removeWords() and this function removes some information from the String.
For example if I pass:
"I Have a Headach"
the function should return:
"Headach"
However, my function is not working:
public class WordChosen extends Activity {
private TextView wordsList;
private String symptom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_chosen);
//Getting String from VoiceRecognition Activity and displaying it
Intent intent = getIntent();
String wordChosen = intent.getExtras().getString("wordChosen");
//casting the string with TextView to display the result
wordsList = (TextView) findViewById(R.id.wordChosen);
Log.v("Word List:", "+++++"+wordChosen);
//Setting text to be displayed in the textView
removeWords(wordChosen);
Log.v("removewords:", "------- message is displayed");
}
public void removeWords(String wordList)
{
ArrayList<String> stopList = null;
stopList.add("i");
stopList.add("have");
stopList.add("a");
ArrayList<String> result = new ArrayList<String>(Arrays.asList(wordList.split(" ")));
for(int i=0; i<result.size();i++)
{
for(int j=0; j<stopList.size();j++)
{
if (result.get(i).equals(stopList.get(j))) {
break;
}
else {
if(j==stopList.size()-1)
{
wordsList.setText(result.get(i));
}
}
}
}
}
}
public static void main(String[] args) {
String word = "I Have a Headach";
String remove = "I Have a ";
System.out.println(removeWords(word, remove));
}
public static String removeWords(String word ,String remove) {
return word.replace(remove,"");
}
output : Headach

Categories