If Statement Not Executed in AutocompleteTextView - android-studio

I'm new to Android Studio and currently working on my first app. Thanks to numerous examples on here i have managed to catch up on the basics very quickly. I now have a problem with my autocompletetextview, i want to get the text selected then use it in a if statement to determine what is shown on the "results" textview. The if statement works fine but only for the "else" part and i can't figure out where i went wrong.
I have commented out the onItemClickListener because the "testfoodph" method does the same.
Here is the activity code:
public class phTester extends AppCompatActivity {
Intent intent = getIntent();
AutoCompleteTextView text;
MultiAutoCompleteTextView text1;
TextView results;
String foodies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ph_tester);
String[] foods = getResources().getStringArray(R.array.foodlist);
text=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
text.setAdapter(adapter);
text.setThreshold(1);
results=(TextView)findViewById(R.id.phResults);
foodies = text.getText().toString();
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if (foodies.equalsIgnoreCase("Mango")) {
//results.setText(getString(R.string.phAlk));
}
//else {
//results.setText(getString(R.string.Error));
//}
//}
});
}
public void TestFoodPH(View view) {
if (foodies.equalsIgnoreCase("Mango")) {
results.setText(getString(R.string.phAlk));
}
else {
results.setText(getString(R.string.Error));
}
}

Related

setLayout not inflating correct xml layout?

been alright so far. I try to use docs or find my issues.
However my mainActivity has 4 buttons. These buttons depending on which view is clicked passes the R.id.button. I pass this value into an intent which Activity2 uses bundle to get id integer. I then setContentView using this.
However im having issues getting correct view to inflate now, it seems like its loading an old layout. My aim is to inflate 3 separate layout on Activity2 depending which button was clicked.
I know my other other button does inflate another activity and get proper xml layout.
Why are my other 3 buttons not inflating on Activity2 properly?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pizza;
Button hamburger;
Button icecream;
Button history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.buttonPizza);
hamburger = findViewById(R.id.buttonBurger);
icecream = findViewById(R.id.buttonIceCream);
history = findViewById(R.id.buttonHistroy);
pizza.setOnClickListener(this);
hamburger.setOnClickListener(this);
icecream.setOnClickListener(this);
history.setOnClickListener(this);
}
#Override
public void onClick(View v){
int idView = v.getId();
switch(v.getId()) {
case R.id.buttonBurger : startOrderActivity(R.layout.burger_layout);
makeToast(idView);
break;
case R.id.buttonPizza : startOrderActivity(R.layout.pizza_layout);
makeToast(idView);
break;
case R.id.buttonIceCream : startOrderActivity(R.layout.icecream_layout);
makeToast(idView);
break;
case R.id.buttonHistroy : startOrderActivity(R.layout.history_layout);
makeToast(idView);
break;
}
}
private void startOrderActivity(int id){
if(id != R.layout.history_layout) {
Intent intentOrder = new Intent(this, MakeOrderActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
else {
Intent intentOrder = new Intent(this, OrderHistoryActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
}
public void makeToast(int id){
String txt = String.valueOf(id);
Toast newToast = Toast.makeText(getApplicationContext(),txt,Toast.LENGTH_LONG);
newToast.show();
}
}
public class MakeOrderActivity extends AppCompatActivity {
Button placeOrderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
int layoutNum = data.getInt("layout");
setContentView(layoutNum);
placeOrderButton = findViewById(R.id.placeOrder);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
public void onCheckboxClicked(View view){
}
}
Answer is to create a View which is created by getInflator.
https://stackoverflow.com/a/17070408/8443090

Android Studio - same menu for all activities (Navigation Drawer)

I'm new to Android Studio (and also pretty new to javascrips), so this might be a stupid question.
I do not want to maintain the same code more than once if possible, which is why I am trying to create a navigation-menu, to be used in all my activities.
So far I have created a "BaseActivity" that contains all the functions for my menu. This one works fine.
Now my problem:
In my other activities I can not get it to show up (not without issues anyway). It seems to me like it overwrites the layout.
My base ("BaseActivity"):
public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.Open, R.string.Close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView NavigationView=(NavigationView)findViewById(R.id.navigation_view);
NavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void setContentView(int layoutResID)
{
super.setContentView(R.layout.activity_base);
ViewGroup content = (ViewGroup) findViewById(R.id.navigation_view);
getLayoutInflater().inflate(layoutResID, content, true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id==R.id.nav_Home) {
startActivity(new Intent(this, MainActivity.class));
}
else
if(id==R.id.nav_Activity1) {
startActivity(new Intent(this, Activity1.class));
}
return super.onOptionsItemSelected(item);
}
}
If I change the app to start through this activity the menu works, but the layout seems to be overwritten (it's empty).
When I try to run it normally (MainActivity), I get some issues.
MainActivity:
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }}
The menu-icon is there, but I can not click on it.
If I remove the code in my MainActivity it works as before (with the layout problem).
I have tried something like this:
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup content = (ViewGroup) findViewById(R.id.navigation_view);
getLayoutInflater().inflate(R.layout.activity_main, content, true);
}}
Not working well. The layout from MainActivity seems to be implemented in the menu. It looks very strange.
Any ideas how to solve my problem?

Counting number of times android app goes into background

I'm developing an app which counts number of times the app goes to the background. It also retains the values when the orientation is changed. Though I have it working of all use cases, I have one use case which does not work.
Case : When I press the home button, change the phone's orientation and reopen the app, It does open in landscape mode but, the background count does not increase.
I have tried setting values in all the life cycle methods. It doesn't work. Hope somebody can help me with this.
`
public class MainActivity extends AppCompatActivity {
private int clickCount =0, backgroundCount = 0;
TextView tvClickCountValue, tvBackgroundCountValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null){
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
setContentView(R.layout.activity_main);
tvClickCountValue = (TextView) this.findViewById(R.id.tvClickCountValue);
tvBackgroundCountValue = (TextView) this.findViewById(R.id.tvBackgroundCountValue);
setView(MainActivity.this);
}
public void onClick(View v){
clickCount += 1;
tvClickCountValue.setText(Integer.toString(clickCount));
}
public void setView(Context ctx){
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onStop() {
super.onStop();
backgroundCount += 1;
}
#Override
protected void onResume() {
super.onResume();
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", clickCount);
outState.putInt("BGCOUNT", backgroundCount);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
}
This article contains useful information: https://developer.android.com/guide/topics/resources/runtime-changes.html especially in the section about Handling The Change.
Try handling it on onConfigurationChanged() of you have disabled Activity restarts on orientation changes. Otherwise, probably through this article you will find which case applies to your scenario.
By reading the problem description, I am assuming that if you don't rotate the device the application works as intended.
you need to persist the count in the SharedPreferences. each time you reopen the app read the last value from the SharedPreferences. And increment and save to SharedPreferences each time the app is hidden.
Then you can count the with #kiran code:
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;
#Override
protected void onStart() {
if (!isAppInFg) {
isAppInFg = true;
isChangeScrFg = false;
onAppStart();
}
else {
isChangeScrFg = true;
}
isScrInFg = true;
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (!isScrInFg || !isChangeScrFg) {
isAppInFg = false;
onAppPause();
}
isScrInFg = false;
}
public void onAppStart() {
// app in the foreground
// show the count here.
}
public void onAppPause() {
// app in the background
// start counting here.
}
}

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

How to send data in ListView dynamicaly in android.?

My question is how do i send data written in EditText of dialogue box by clicking button and display it on LIstView of Main Activity. ?
public class TaskDetailsActivity extends Activity implements OnClickListener{
String[] timepass= new String[100];
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskdetails);
//timepass[0] = "sidd";
/*ListView tasklist= (ListView)findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.insideaddtask, R.id.tp, timepass);
tasklist.setAdapter(adapter);*/
}
public void addnewtask(View view)
{
showDialog(1);
}
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog=null;
switch (id)
{
case 1: dialog = new Dialog(TaskDetailsActivity.this);
dialog.setContentView(R.layout.addtask);
Button task_add_ok = (Button)findViewById(R.id.btn_ok);
task_add_ok.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText writetask = (EditText)findViewById(R.id.txt_writetask);
String data = writetask.getText().toString();
timepass[0] = data;
}
});
break;
default:
break;
}
return dialog;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
}
you can use any adapter for this arrayadapter of type string...
and use the button's onclick method to populate the listview...
below link provides a good example...
http://android.amberfog.com/?p=296
www.androidhive.info/2011/10/android-listview-tutorial/

Resources