Store a string message after using onItemLongClick (Android) - android

I want to store the fMessage to the variable favoritekafe and return the favoritekafe after the onItemLongClick method ends.
Is that possible in any way?
OR can i accomplish with a different way to return a variable except true/false from "onItemLongClick" method?
Thats my code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.SharedPreferences;
public class MainActivity2 extends AppCompatActivity {
ListView kafeteries;
String favoritekafe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coffee);
if (favoritekafe==null) {
Toast.makeText(getApplicationContext(), "you don't have a favorite
caffe yet", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), favoritekafe,
Toast.LENGTH_SHORT).show();
}
/* oi kafeteries se lista */
kafeteries = (ListView) findViewById(R.id.kafeteries);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>
(MainActivity2.this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.kafeteries_syros));
kafeteries.setAdapter(mAdapter);
// mnmta TOAST otan kanw click kapoio stixeio tis listas */
kafeteries.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String sMessage = "";
switch(position) {
case 0: sMessage = "Coffee and drinks with hospitable locals\nArea:Ermoupoli\nPhone:2281083354"; break;
case 1: sMessage = "Coffee in the narrow streets of the city\nArea:Ermoupoli\nPhone:2281079225"; break;
case 2: sMessage = "The smallest and most adorable coffee in town\nArea:Ermoupoli\nPhone:2281300880"; break;
case 3: sMessage = "Coffee and snacks at the city's harbor\nArea:Ermoupoli\nPhone:2281076144"; break;
case 4: sMessage = "The city's most famous café\nArea:Ermoupoli\nPhone:2281085337"; break;
}
Toast.makeText(getApplicationContext(), sMessage, Toast.LENGTH_LONG).show();
}
});
// prospathia gia long clik add sta favorite kai save*/
kafeteries.setLongClickable(true);
kafeteries.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long id) {
// prepei na vrw ena tropo na epistrefw kai to position gia na apothikevw tin agapimeni epilogi */
String fMessage = "";
switch(position) {
case 0: fMessage = "Boheme del mar is your favorite caffe"; break;
case 1: fMessage = "Jar is favorite caffe"; break;
case 2: fMessage = "Kouchico is your favorite caffe"; break;
case 3: fMessage = "Okio is your favorite caffe"; break;
case 4: fMessage = "Plaza is your favorite caffe"; break;
}
Toast.makeText(getApplicationContext(), fMessage, Toast.LENGTH_SHORT).show();
final SharedPreferences prefs=getApplicationContext().getSharedPreferences("settings",MODE_PRIVATE);
prefs.edit().putString(favoritekafe,fMessage).commit();
return true;
}
});
}
}

Create a function inside your class
void gotStringFromLongClick(String fMessage){
favoritekafe=fMessage;
// do anything else you want here
}
and call it like gotStringFromLongClick(fMessage); from outside switch
String sMessage = "";
switch(position) {
case 0: sMessage = "Coffee and drinks with hospitable locals\nArea:Ermoupoli\nPhone:2281083354"; break;
case 1: sMessage = "Coffee in the narrow streets of the city\nArea:Ermoupoli\nPhone:2281079225"; break;
case 2: sMessage = "The smallest and most adorable coffee in town\nArea:Ermoupoli\nPhone:2281300880"; break;
case 3: sMessage = "Coffee and snacks at the city's harbor\nArea:Ermoupoli\nPhone:2281076144"; break;
case 4: sMessage = "The city's most famous café\nArea:Ermoupoli\nPhone:2281085337"; break;
}
gotStringFromLongClick(fMessage);
// save value to preference
SharedPreferences.Editor editor = getSharedPreferences("pref", MODE_PRIVATE).edit();
editor.putString("data", fMessage);
editor.commit();
Retrieve value in onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coffee);
favoritekafe = getSharedPreferences("pref", MODE_PRIVATE).getString("data", null);
if (favoritekafe==null) {
Toast.makeText(getApplicationContext(), "you don't have a favorite
caffe yet", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), favoritekafe,
Toast.LENGTH_SHORT).show();
}

You can store it in SharedPreference file.
inside your onLongClickListener do this
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putString("fav_kafe", favoritekafe).commit();
then in onCreate before making the Toast load it to fafavoritekafe
like this
favoritekafe=PreferenceManager.getDefaultSharedPreferences(context)
.getString("fav_kafe", "nothing");
if (favoritekafe.equals("nothing") {
Toast.makeText(getApplicationContext(), "you don't have a favorite
caffe yet", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), favoritekafe,
Toast.LENGTH_SHORT).show();
}

Related

FirebaseTranslatorOptions.Builder object is not taking input from dropdownmenu (Spinner) Firebase Translate text in Android

I have developed an App in Android which translates text (from EditText), Application uses Firebase API. it translates successfully when I select Source and Target Language in hard code. (FirebaseTranslatorOption's setSource and setTarget language settings even integer code i.e. EN (11), FR(17) etc. but it is not taking any dynamic input from Spinner object's setOnItemSelectedListener.
'''
//Spinners itemselection events
input_lang_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position),
Toast.LENGTH_SHORT).show();
selected_source_lang = parent.getItemAtPosition(position).toString();
switch (position){
case 0:
Toast.makeText(getApplicationContext(),"Plz select a language",Toast.LENGTH_LONG).show();
case 1:
SourceLangCode=11;
break;
case 2:
SourceLangCode=17;
break;
case 3:
SourceLangCode=56;
break;
case 4:
SourceLangCode=48;
break;
case 5:
SourceLangCode=9;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(),"Plz select a language",Toast.LENGTH_LONG).show();
}
});
//end of input language selection
output_lang_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position),
Toast.LENGTH_SHORT).show();
selected_target_lang = parent.getItemAtPosition(position).toString();
switch (position){
case 0:
Toast.makeText(getApplicationContext(),"Plz select a language",Toast.LENGTH_LONG).show();
case 1:
targetLangCode=11;
break;
case 2:
targetLangCode=17;
break;
case 3:
targetLangCode=56;
break;
case 4:
targetLangCode=48;
break;
case 5:
targetLangCode=9;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(),"Plz select a language",Toast.LENGTH_LONG).show();
}
});//end of output language selection
//firebaseTranslatorOptions object
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(SourceLangCode) //this is not taken as I select item
.setTargetLanguage(targetLangCode) //item selection is working
.build();
final FirebaseTranslator languageTranslator =
FirebaseNaturalLanguage.getInstance().getTranslator(options);
'''

Setting views as global variables android

I have three functions in my Main class, onCreate,onClick and click, I have two options, declare TextViews and some other views at the beginning of the project as global variables, which means they will stay in the entire app lifetime, or get them separately in each function(will cause the computer to work a bit more but the variables will not stay in memory the whole time). To describe the question further:
OPTION 1:
public static final int L = 6;
TextView[] textViews = new TextView[L];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
int[] digits = {rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)};
for (int i = 0; i < L; i++) {
textViews[i] = (TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(i), "id", getPackageName()));
textViews[i].setOnClickListener(this);
textViews[i].setText(String.valueOf(digits[i]));
}
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(0);
break;
case R.id.num1:
click(1);
break;
case R.id.num2:
click(2);
break;
case R.id.num3:
click(3);
break;
case R.id.num4:
click(4);
break;
case R.id.num5:
click(5);
break;
}
}
public void click(int clicked) {
textViews[clicked].setText("Clicked");
}
OPTION 2: (Note to shorten your time - the change is in the last function).
public static final int L = 6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
int[] digits = {rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)};
for (int i = 0; i < L; i++) {
textViews[i] = (TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(i), "id", getPackageName()));
textViews[i].setOnClickListener(this);
textViews[i].setText(String.valueOf(digits[i]));
}
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(0);
break;
case R.id.num1:
click(1);
break;
case R.id.num2:
click(2);
break;
case R.id.num3:
click(3);
break;
case R.id.num4:
click(4);
break;
case R.id.num5:
click(5);
break;
}
}
public void click(int clicked) {
((TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(clicked),"id",getPackageName())).setText("Clicked");
}
Take into consideration I have more than a TextView array, and in some function I have to get 5 views again, will it be better to declare them as global variables? I read somewhere most of the time using global variables is not good and it is against the whole idea of functions, but it seems more simple here.. Sorry about my English and thank you all.
First off, you do not need to worry about performance issues if the textViews object is declared globally. It is minuscule.
Now in your code,if the only reason to declare textViews array object is to reference it in click() method, then there is no need of declaring it globally.
Instead, you can pass the view object provided by the overridden onClick() method to your click() method.
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(view);
break;
case R.id.num1:
click(view);
break;
case R.id.num2:
click(view);
break;
case R.id.num3:
click(view);
break;
case R.id.num4:
click(view);
break;
case R.id.num5:
click(view);
break;
}
}
public void click(View viewClicked) {
((TextView))viewClicked.setText("Clicked")
}

Linking a dialog box with ListActivity

I am trying to get well versed with ListAvtivity. I have written some code that renders a List and when you click an Item in the List, you are taken to an Activity that gives some arbitrary information.
I am trying to figure some way in which, if the user click on an Item in the list, he is shown a Dialog Box with some information instead of going to a whole new Activity.
Source :
package com.mavenmaverick.listviewtest;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class ActivityExample extends ListActivity{
static final String[] CHOICES = new String[]{
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Saturn",
"Uranus",
"Neptune",
"Pluto",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
switch (arg2) {
case 0:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 1:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 2:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 3:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 4:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 5:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 6:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 7:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
case 8:
startActivity(new Intent(ActivityExample.this,TestActivity.class));
break;
default:
break;
}
}
});
}
}
You can directly fetch your content in the onItemClick. Use the parent.getItemAtPosition() to do this. Since you are filling in your ListView with string arrays, the getItemAtPosition will return a string.
Your code should look like this:
getListView().setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String content = (String)parent.getItemAtPosition(position);
// do something with the dialog
showDialog(content);
}
}
You should google around ListView some more.
You can use/create a dialog within your onItemClick and set the title to the name of the planet and you can even set the view of the dialog to the style you want.
sample:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
switch (arg2) {
case 0:
Dialog dialog = new Dialog(this);
dialog.setTitle(CHOICES[args]);
dialog.setContentView(R.layout.your_layout_to_dialog); //<-- if you want to add some view to your dialog
dialog.show();
break;
Try this dude it will help you......
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Youractivity.this);
// Setting Dialog Title
alertDialog.setTitle("AlertDialog");
switch (arg2) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
break;
}
// Setting Dialog Message
alertDialog.setMessage("A Planet in the Solar System"+arg2+"listview Item clicked");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}

How do I pass the additional parameter to the onClick method?

I want to pass a from my method to the button clicked method.
Method that generates a:
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String str = arg0.getItemAtPosition(arg2).toString();
double a = 0;
switch(arg2){
case 0:
a = 4;
break;
case 1:
a = 3.75;
break;
case 2:
a = 3.50;
break;
case 3:
a = 3.25;
break;
case 4:
a = 3;
break;
case 5:
a = 2.75;
break;
case 6:
a = 2.5;
break;
case 7:
a = 2.25;
break;
}
Button clicked method
public void button(View v){
}
Make a a field of your activity instead of an instance variable like so:
public class MyActivity extends Activity {
double a = 0;
...
}

Android Mapping Remote Control Keys with Virtual Key Board and append the text in edittext

I am working on a project based on Mapping the Remote control keys with android device.Here I can able to get the keycodes of Remote keys and return values for it based on the key codes.But the problem is, I don't know how to append the values inside the edit text.If I pressed the remote keys, it always returns numbers only.Guide me in a right way to make this work. Thanks in advance.
Sample Code:
I am having the below code in a Global Activity.And I extended all other Activities from this one.
public String switchedMethod(int key)
{
String letter = null;
switch(key)
{
case 9:
letter = "a";
break;
case 10:
letter = "b";
break;
case 11:
letter = "c";
break;
case 12:
letter = "d";
break;
case 13:
letter = "e";
break;
case 14:
letter = "f";
break;
case 15:
letter = "g";
break;
case 16:
letter = "h";
break;
}
Log.v("LETTER", ""+letter);
return letter;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
Log.v("KEYCODE", ""+keyCode);
switchedMethod(keyCode);
return super.onKeyDown(keyCode, event);
}
//Code Related to Edit Text
public class SettingsSubElementCreator extends GlobalActivity
{
protected void handleSDEditText(int optionItemsCurrentItemIndex)
{
LinearLayout subLayout = new LinearLayout(this);
subLayout.setOrientation(LinearLayout.VERTICAL);
subLayout.removeAllViews();
createButtons();
// I NEED TO APPEND THE TEXT FOR THE BELOW EDITTEXT VIEW
final EditText SDEditText = new EditText(this);
SDEditText.setTypeface(boldTypeface);
subLayout.addView(SDEditText);
subLayout.addView(okcancelButtonLayout);
final ModifySettingsDialog dialog = new ModifySettingsDialog(this,
R.string.video_aspect_adjustment_sd,
optionItemsCurrentItemIndex, subLayout, false);
dialog.show();
okButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(view.getContext(),"inside video aspect adjustment sd"+ SDEditText.getText(), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
}

Categories

Resources