How use if/else output in other class - android

I try have departureCity value (it set in if/else of onItemSelected method in FlightCityOnItemSelectedListener class) in my FlightAct activity (value will use URL to parse json).
Now how can I get departureCity value all of my FlightAct.java ? or other activities?
because I will use many variables out of loops that they are in methods.how use them out of methods?
package ir.safarbazha.safarbazha.Core.adapter;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
public class FlightCityOnItemSelectedListener
implements AdapterView.OnItemSelectedListener {
String departureCity;
public void onItemSelected(
AdapterView<?> parent,
View view,
int pos,
long id
) {
String selectedCity = parent.getItemAtPosition(pos).toString();
if (selectedCity.equals("آبادان")) {
departureCity="ABD";
Toast.makeText(parent.getContext(),
"آنچه انتخاب شد : " +
parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
================================================================================
package ir.safarbazha.safarbazha.Acts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.adapter.FlightCityOnItemSelectedListener;
import ir.safarbazha.safarbazha.R;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class FlightAct extends AppCompatActivity {
Context currentActivity=FlightAct.this;
ActionBar mainActionbar;
ImageView mainToolbarMenu;
ImageView mainToolbarHome;
ImageView mainToolbarAbout;
ImageView mainToolbarAccount;
ImageView mainToolbarSearch;
DrawerLayout mainDLayout;
DrawerCustomListAdapter mainDCLAdapter;
String[] mainDitems;
List<String> mainDItems;
ListView mainDLV;
//Just For This Activity...
Spinner departureCity , arrivalCity;
TextView departureDate , arrivalDate , capacityCount;
RadioButton radioButtonOneWayFlightType , radioButtonRoundTripFlightType;
Button btnSubmitFlightForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")){
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_flight);
}
setContentView(R.layout.act_flight);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainActionbar=getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
mainActionbar.setCustomView(v);
mainActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu=(ImageView)findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mainDLayout.isDrawerOpen(GravityCompat.START))
mainDLayout.closeDrawer(GravityCompat.START);
else mainDLayout.openDrawer(GravityCompat.START);
}
});
//Main ToolBar Home Image Object...
mainToolbarHome=(ImageView)findViewById(R.id.toolbar_home_icon);
mainToolbarHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,HomeAct.class));
}
});
//Main ToolBar About Image Object...
mainToolbarAbout=(ImageView)findViewById(R.id.toolbar_about_icon);
mainToolbarAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,AboutAct.class));
}
});
//Main ToolBar Account Image Object...
mainToolbarAccount=(ImageView)findViewById(R.id.toolbar_account_icon);
mainToolbarAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,AccountAct.class));
}
});
//Main ToolBar Search Image Object...
mainToolbarSearch=(ImageView)findViewById(R.id.toolbar_search_icon);
mainToolbarSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,SearchAct.class));
}
});
//Set Custom Navigation Drawer...
mainDLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mainDLV=(ListView)findViewById(R.id.drawer_lv);
mainDitems= getResources().getStringArray(R.array.main_titles);
mainDItems=new ArrayList<String>(Arrays.asList(mainDitems));
mainDCLAdapter=new DrawerCustomListAdapter(this,mainDItems);
mainDLV.setAdapter(mainDCLAdapter);
mainDLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = getResources().getStringArray(R.array.main_titles)[position];
if (position==0)
startActivity(new Intent(currentActivity, HomeAct.class));
else if (position == 1)
startActivity(new Intent(currentActivity,AboutAct.class));
else if (position == 2)
startActivity(new Intent(currentActivity, PostAct.class));
else if (position == 3)
Snackbar.make(view, "کاربر گرامی شما هم اکنون در *پرواز ها* برنامه سفر باز ها هستید!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
else if (position == 4)
startActivity(new Intent(currentActivity, ProductAct.class));
else if (position == 5)
startActivity(new Intent(currentActivity, AccountAct.class));
else if (position == 6)
startActivity(new Intent(currentActivity, ContactAct.class));
}
});
//Just For This Activity...
addListenerOnButton();
addListenerOnSpinnerItemSelection();
//Selected Departure And Arrival Airports...
departureCity=(Spinner)findViewById(R.id.departure_city);
arrivalCity=(Spinner)findViewById(R.id.arrival_city);
//Selected Flight Type (OneWay or RoundTrip)...
radioButtonOneWayFlightType=(RadioButton)findViewById(R.id.btnRadioOneWayFlightType);
radioButtonRoundTripFlightType=(RadioButton)findViewById(R.id.btnRadioRoundTripFlightType);
radioButtonOneWayFlightType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrivalDate.setVisibility(View.GONE);
}
});
radioButtonRoundTripFlightType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrivalDate.setVisibility(View.VISIBLE);
}
});
//Selected Departure And Arrival Date...
departureDate=(TextView)findViewById(R.id.departure_date);
arrivalDate=(TextView)findViewById(R.id.arrival_date);
//Selected Count Of Capacity...
capacityCount=(TextView)findViewById(R.id.capacity_count);
}
//Set Custom Font For All Views in Core/app/AppController ...
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
//Just For This Activity...
//DropDown City Choosing...
public void addListenerOnSpinnerItemSelection() {
departureCity = (Spinner) findViewById(R.id.departure_city);
arrivalCity = (Spinner)findViewById(R.id.arrival_city);
departureCity.setOnItemSelectedListener(new FlightCityOnItemSelectedListener());
arrivalCity.setOnItemSelectedListener(new FlightCityOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
departureCity = (Spinner) findViewById(R.id.departure_city);
arrivalCity = (Spinner) findViewById(R.id.arrival_city);
btnSubmitFlightForm = (Button) findViewById(R.id.btnSubmitFlightActForm);
btnSubmitFlightForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(currentActivity,"OnClickListener : "
+"\nشهر مبدا : "+
String.valueOf(departureCity.getSelectedItem())
+
"\nشهر مقصد : "+
String.valueOf(arrivalCity.getSelectedItem())
,
Toast.LENGTH_SHORT).show();
}
});
}
}

Save the required data in a class variable.
You can use a bundle to send the data to other activities from which you can access that data.
Code example to store the data in the intent used to launch the second activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putString("stringvalue", strValue);
b.putLong("longvalue", lngValue);
b.putDouble("doublevalue", doubValue);
b.putBoolean("boolvalue", boolValue);
intent.putExtras(b);
startActivity(intent);
Code to get the data from the bundle in the second activity (this code to be placed in the onCreate() method):
// get the Intent that started this Activity
Intent in = getIntent();
Bundle b = in.getExtras();
String strValue= b.getString("stringvalue");
long longValue = b.getLong("longvalue");
double doubleValue= b.getDouble("doublevalue");
boolean boolValue= b.getBoolean("boolvalue");

You can make it static ,so you can use it anywhere in your other classes.
change "public static String departureCity" instead of "String departureCity";
then you can call it like that : FlightCityOnItemSelectedListener.departureCity
(without instantiate FlightCityOnItemSelectedListener).

Related

Get single JSON value from response Retrofit

Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));

How to select single item from listview and display resulted name of row in another activity

I got problem when trying to get checked item from listView through predefined xml layout simple_list_item_single_choice and select item then set text of a TextView that is in another activity.
This is my showMyUI method that call from MainActivity on click of TextView
dateRange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Range clicked",Toast.LENGTH_SHORT).show();
DateRangeClass day=new DateRangeClass(MainActivity.this,dayRangeSelected);
day.showMyUI();
overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
}
});
And my DateRangeClass is
package tutorial.projecttwofilter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DateRangeClass {
Context context;
LinearLayout backButton;
ListView rangeList;
TextView rangeText;
String[] dateRangeData= new String[]{"Next 7 Days", "Next 14 Days", "Next 30 Days"};
public DateRangeClass(Context context,TextView rangeText) {
this.context = context;
this.rangeText=rangeText;
}
public void showMyUI(){
((Activity)context).setContentView(R.layout.daterange);
backButton= (LinearLayout) ((Activity)context).findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
rangeList= (ListView) ((Activity)context).findViewById(R.id.dateRangeList);
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, dateRangeData);
rangeList.setAdapter(adapter);
rangeList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rangeList.setItemChecked(position, true);
if(rangeList.isItemChecked(position))
Toast.makeText(context, "Checked item is"+rangeList.getCheckedItemPosition(), Toast.LENGTH_SHORT).show();
rangeText.setText("You new Change "+rangeList.getCheckedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
}
Create DateRangeClass as an activity not as normal class and pass the information using bundle. As i can see you are passing textview instead of that you can pass text as string and can show in second activity.
To transfer data
String textToBesend = "Text from textview";
Intent i = new Intent(this, DateRangeActivity.class);
i.putExtra("text", textToBesend);
startActivity(i);
and to recieve data in DateRangeActivity write this in oncreate method.
Intent intent = getIntent();
String textPassedFromFirstActivity = intent.getExtras().getString("text");
You can refer below tutorial for your purpose hope it helps.
passing data to activity from listview
You have not started your activity.
Use startActivity and putIntent method on button click and in your second activity use getIntent method to display the text.

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

android action bar menu button event handling issue

I have action button in my fragment, i follow some tutorial in internet and i have managed to show my action button in my fragment. but for unknown reason when i tap the action button nothing happened.
This is my xml menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<item android:id="#+id/send_card"
android:icon="#drawable/btn_add"
android:title="send card"
yourapp:showAsAction="always"
/>
</menu>
package com.dycode.durexlovers.fragment;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.dycode.durexlovers.R;
import com.dycode.durexlovers.adapter.HorizontalListViewCardAdapter;
import com.dycode.durexlovers.adapter.MomentAdapter;
import com.dycode.durexlovers.adapter.SpiceItUpAdapter;
import com.dycode.durexlovers.adapter.ViewPagerAdapter;
import com.dycode.durexlovers.api.CardApi;
import com.dycode.durexlovers.api.MomentApi;
import com.dycode.durexlovers.card.PreviewCard;
import com.dycode.durexlovers.card.SendCard;
import com.dycode.durexlovers.dao.CardDao;
import com.dycode.durexlovers.dao.MomentDao;
import com.dycode.durexlovers.utils.Constant;
import com.dycode.durexlovers.utils.SessionManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.HListView;
/**
* Created by Minecraft on 06/01/2015.
*/
public class SpiceItUpFragment extends Fragment {
LinearLayout stripRomantic, stripRomanticAct, stripTease, stripTeaseAct, stripIntimate, stripIntimateAct;
Button btnRomantic, btnTease, btnIntimate, btnNext, btnBack, btnSendCard;
HListView hListView;
private CardApi cardApi;
private List<CardDao> listCard = new ArrayList<CardDao>();
HorizontalListViewCardAdapter adapter;
ProgressDialog dialog;
SessionManager sessionManager;
String email;
TextView tvNameCard, tvDescCard;
ImageView ivCard;
AQuery aQuery;
int pos;
String categoryCard;
public SpiceItUpFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spice_it_up, container, false);
stripRomantic = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic);
stripRomanticAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic_active);
stripTease = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease);
stripTeaseAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease_active);
stripIntimate = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate);
stripIntimateAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate_active);
btnRomantic = (Button) rootView.findViewById(R.id.btnRomantic);
btnTease = (Button) rootView.findViewById(R.id.btnTease);
btnIntimate = (Button) rootView.findViewById(R.id.btnIntimate);
btnNext = (Button) rootView.findViewById(R.id.btnNext);
btnBack = (Button) rootView.findViewById(R.id.btnBack);
btnSendCard = (Button) rootView.findViewById(R.id.btnSendCard);
hListView = (HListView) rootView.findViewById(R.id.hListView);
tvNameCard = (TextView) rootView.findViewById(R.id.tvNameCard);
tvDescCard = (TextView) rootView.findViewById(R.id.tvDescCard);
ivCard = (ImageView) rootView.findViewById(R.id.ivCard);
aQuery = new AQuery(getActivity());
cardApi = new CardApi(getActivity(), cardListener);
adapter = new HorizontalListViewCardAdapter(getActivity(), listCard);
hListView.setAdapter(adapter);
sessionManager = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
email = user.get(sessionManager.KEY_EMAIL);
categoryCard = "romantic";
cardApi.callApiCard(email, categoryCard);
//hListView.setAdapter( new ArrayAdapter<String>( getActivity(), R.layout.card_horizontal_list_item, activities ) );
btnRomantic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("romantic")){
categoryCard = "romantic";
stripRomantic.setVisibility(View.INVISIBLE);
stripRomanticAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email, categoryCard);
}
}
});
btnTease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("tease")){
categoryCard = "tease";
stripTease.setVisibility(View.INVISIBLE);
stripTeaseAct.setVisibility(View.VISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
btnIntimate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("intimate")){
categoryCard = "intimate";
stripIntimate.setVisibility(View.INVISIBLE);
stripIntimateAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
hListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
pos = position;
tvNameCard.setText(listCard.get(position).getNameCard());
tvDescCard.setText(listCard.get(position).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(position).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos < listCard.size()-1) {
pos = pos + 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos > 0) {
pos = pos - 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnSendCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
CardApi.ApiResultListener cardListener = new CardApi.ApiResultListener() {
#Override
public void onApiResultOk(List<CardDao> listData) {
if (dialog != null)
dialog.dismiss();
listCard.clear();
listCard.addAll(listData);
adapter.notifyDataSetChanged();
pos = listCard.size() / 2;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
#Override
public void onApiPreCall() {
dialog = ProgressDialog.show(getActivity(), "", "loading...");
}
#Override
public void onApiResultError(String errorMessage) {
showDialogNotification(errorMessage);
if (dialog != null)
dialog.dismiss();
}
};
private void showDialogNotification(String message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setTitle("Notification");
alertDialogBuilder.setMessage(message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.send_card:
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Thank for your help
change your method like below.you need to call super.onCreateOptionsMenu like below
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
and set setHasOptionsMenu(true); in your oncreateview befor return v;

onActivityResult Is not responding when choosing from a list

Hi Guys I am new with android programming and Java. I am trying to make a travel app. My issue is that how do I pass data from the selected item from the list to the editText filed. This is out I have done so far.. Pls. be kind I am newbee
The activity class that uses the ListActivity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectStationActivity extends ListActivity {
String stations[] = { "Acton Main Line","Ealing","Great Western","Albany Park"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stations);
setListAdapter(adapter);
}
protected void OnListItemClick(ListView l, View v, int position, long id) {
String values = stations[(int) id];
Intent result = new Intent().putExtra("SELECTED_STATION_NAME", values);
setResult(RESULT_OK, result);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_station, menu);
return true;
}
The main class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TravelActivity extends Activity {
// The request code for the selectChkInBt
protected static final int SelectChkin_REQUEST_CODE = 1;
// The request code for the selectChkOutBt
protected static final int SelectChkout_REQUEST_CODE = 2;
private String checkinStation;
private String checkoutStation;
private Button checkinButton, checkoutButton, selectChkInButton, selectChkOutButton;
private EditText checkinEditText, checkoutEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel);
checkinButton = (Button) findViewById(R.id.btCkIn);
checkoutButton = (Button) findViewById(R.id.BtChkOut);
selectChkInButton = (Button) findViewById(R.id.btselectChkIn);
selectChkOutButton = (Button) findViewById(R.id.btselectChkOut);
checkinEditText = (EditText) findViewById(R.id.EditTxtChkIn);
checkoutEditText = (EditText) findViewById(R.id.EditTxtChkOut);
checkinButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkinEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-in Station", Toast.LENGTH_LONG).show();
} else {
checkinStation = checkinEditText.getText().toString();
// Enable the check-out EditText and Button
checkinEditText.setEnabled(false);
checkinEditText.setTextColor(Color.CYAN);
checkinButton.setEnabled(false);
// Disable the check-in- EdiText AND Button
checkoutEditText.setEnabled(true);
checkoutButton.setEnabled(true);
checkoutEditText.requestFocus();
}
}
});
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkoutEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-Out station", Toast.LENGTH_LONG)
.show();
} else {
checkoutStation = checkoutEditText.getText().toString();
// Clear edit Text
checkoutEditText.setText("");
// Enable the check-in EditText and Button
checkoutEditText.setEnabled(false);
checkoutButton.setEnabled(false);
/*
* Disable the check-out EditText and Button, to allow the
* eternal cycle of checking in and out to commence once again */
checkinEditText.setText("");
checkinEditText.setEnabled(true);
checkinButton.setEnabled(true);
checkinEditText.requestFocus();
Toast.makeText(getApplicationContext(),
"Travel information added!", Toast.LENGTH_SHORT)
.show();
}
}
});
I could implement a inner class for the two select buttons but i have diffculties to do it.Pls. provide some help how I could implement it thanks.
selectChkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,
SelectStationActivity.class);
startActivityForResult(intent, SelectChkin_REQUEST_CODE);
}
});
selectChkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,SelectStationActivity.class);
startActivityForResult(intent, SelectChkout_REQUEST_CODE);
}
});
}
The onActivityResult is not responding here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== RESULT_OK){
if (requestCode == 1) {
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "Recipt");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean OnMenuItemSelected(int featureId, MenuItem item) {
String Recipt = "Recipt" + item.getItemId() + "\nCheck-in: "
+ checkinStation + "\nCheck-Out: " + checkoutStation;
Toast.makeText(getApplicationContext(), Recipt, Toast.LENGTH_LONG)
.show();
return true;
}
protected void OnSaveInstanceState(Bundle outState) {
outState.putString("lAST_CHECKIN", checkinStation);
outState.putString("lAST_CHECKOUT", checkoutStation);
}
protected void onRestoreInstance(Bundle savedInstanceState) {
checkinStation = savedInstanceState.getString(checkinStation);
checkoutStation = savedInstanceState.getString(checkoutStation);
}
}
You Should use this
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
as
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME").toString());

Categories

Resources