Android Spinner on activity other than starting activity - java

I'm having a bit of an issue, I'm working on a android app that requires a spinner to update a string to your spinner selection, I have it all working and everything, the problem is that I need the spinner on another activity than the starting activity but when I start the app with a different activity than the one with the spinner and activate the array adapter and listener at the same time I switch views to the one with the spinner, the spinner is empty with no choices. I can't for the life of me figure this out. PS, sorry about the weird variable names I get bored and instead of making a proper name I think of something on the spot and come back and change it later. PPS The name of the content view with the spinner is orderpage and the one I want to have start with the app is activity_main PPPS I cut out some methods I deemed irrelevant so there are some variables not used. I attached my code below:
package com.NIQUOLI.Deliveryapp;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.NIQUOLI.Deliveryapp.GMailSender;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Debug;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
public static boolean deeznuts = false;
public static String storenamestring;
public static String namesame;
public static String instructionsame;
public int choice = 0;
private Spinner spinner1;
private Button button = null;
String[] stores;
Spinner sp;
public void cont(View View){
deeznuts = true;
setContentView(R.layout.orderpage);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.orderpage);
button = (Button) findViewById(R.id.send_email);
super.onCreate(savedInstanceState);
sp = (Spinner) findViewById(R.id.sp);
stores = getResources().getStringArray(R.array.stores);
if (deeznuts = true){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,stores);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You selected"+stores[index], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and of course my XML with the s[ommer:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.NIQUOLI.Deliveryapp.SendMailTask" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="#string/order_page"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Space
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:hint="#string/enter_your_name"
android:inputType="text" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/sp"
android:layout_width="388dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/instructions"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.34"
android:ems="10"
android:inputType="textMultiLine" />
<Button
android:id="#+id/send_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/send_order" />
</LinearLayout>

On the 6th line of the onCreate method in the first code sample, if(deeznuts = true) should be if(deeznuts == true).

Related

Retrieve data from ListView items

I made a listview with adapter and each listview item contains four RadioButtons.
What I want to do is to have a button on the listview containing activity.And when I click on that button it will retrieve all checkstate of radiobuttons of each item and send them to other activities.
But I don't know how to retrieve that data although I searched a lot . this is the Activity.java file
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.width;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static android.util.TypedValue.applyDimension;
/**
* Created by jack on 30/08/17.
*/
public class TempActivity extends AppCompatActivity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.s7_1);
ArrayList<String> titlesArray = new ArrayList<>();
titlesArray.add("إيه رأيك في البني آدم اللي شرح الدورة");
titlesArray.add("ايه رأيك في المكان اللي تمت فيه الدورة");
titlesArray.add("الجهة المنظمة اللي عملت الدورة");
titlesArray.add("محتوى الدورة");
titlesArray.add("تقييم عام");
//Initialization of Adapter and ListView and hooking them together
RateAdapter rateAdapter = new RateAdapter(this , titlesArray);
listView = (ListView)findViewById(R.id.rate_listview);
listView.setAdapter(rateAdapter);
Toast.makeText(getBaseContext() , listView.getCount()+"" , Toast.LENGTH_SHORT).show();
}
}
This is my adapter
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class RateAdapter extends ArrayAdapter {
View listItemView;
String currentTitle;
TextView titleTV ;
Context context;
public String a ="test";
public RateAdapter(Context context, ArrayList<String> arrayList) {
super(context, 0, arrayList);
this.context = context;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.n, parent, false);
}
//Declaration for the current title
currentTitle = (String) getItem(position);
//Initializations //Note if radiobuttons are declared as global variables the items are missed up :D
final RadioButton radioVa = (RadioButton) listItemView.findViewById(R.id.rateitems_va);
final RadioButton radioVb = (RadioButton) listItemView.findViewById(R.id.rateitems_vb);
final RadioButton radioVc = (RadioButton) listItemView.findViewById(R.id.rateitems_vc);
final RadioButton radioVd = (RadioButton) listItemView.findViewById(R.id.rateitems_vd);
titleTV = (TextView)listItemView.findViewById(R.id.rateitems_title);
//Setting the title to the TextView
titleTV.setText(currentTitle);
//Setting oncheck listener to permit only one check
//for Va
radioVa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVc.setChecked(false);
}
}
});
//
radioVb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVa.setChecked(false);
radioVc.setChecked(false);
radioVd.setChecked(false);
}
}
});
radioVc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVa.setChecked(false);
radioVb.setChecked(false);
radioVd.setChecked(false);
}
}
});
radioVd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVb.setChecked(false);
radioVc.setChecked(false);
radioVa.setChecked(false);
}
}
});
return listItemView;
}
}
This is the listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="160dp"
android:orientation="vertical"
android:layoutDirection="rtl"
android:background="#fff"
android:paddingBottom="10dp">
<TextView
android:id="#+id/rateitems_title"
android:gravity="center_vertical"
android:paddingRight="15dp"
tools:text="ًWhat do you think about me "
android:textColor="#fff"
android:textSize="13sp"
android:textStyle="bold"
android:background="#277db3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="30dp"/>
<LinearLayout
android:orientation="vertical"
android:padding="30dp"
android:layout_below="#id/rateitems_title"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:background="#drawable/course_items_border_trans"
android:id="#+id/rateitems_va"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="ممتاز"
android:textSize="15sp"
android:paddingRight="5dp"/>
<RadioButton
android:id="#+id/rateitems_vb"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="جيد جدا"
android:textSize="15sp"
android:paddingRight="5dp"/>
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rateitems_vc"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="جيد"
android:textSize="15sp"
android:paddingRight="5dp"/>
<RadioButton
android:id="#+id/rateitems_vd"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="ضعيف"
android:textSize="15sp"
android:paddingRight="5dp"/>
</RadioGroup>
</LinearLayout>
</android.widget.RelativeLayout>
and this is the activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layoutDirection="rtl"
android:background="#fff"
android:paddingBottom="10dp">
<TextView
android:gravity="center_vertical"
android:paddingLeft="15dp"
tools:text="List test"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"
android:background="#277db3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="30dp"/>
<ListView
android:id="#+id/rate_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/the_btn"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.widget.LinearLayout>
Use a model something like
Class Rate{
String title;
int rate;
Rates(String title){
this.title = title;
}
public void setRate(int rate){
this.rate = rate;
}
public String getTitle(){
return this.title;
}
}
Now, inside activity do something like:
List<Rates> rates = new ArrayList<>();
rates.add(new Rates("إيه رأيك في البني آدم اللي شرح الدورة"));
rates.add(new Rates("ايه رأيك في المكان اللي تمت فيه الدورة");
rates.add(new Rates("الجهة المنظمة اللي عملت الدورة"));
rates.add(new Rates("محتوى الدورة"));
rates.add(new Rates("تقييم عام"));
List<String> strings = new ArrayList<>(rates.size());
for (Rate rate : rates) {
strings.add(rate != null ? rate.getTitle() : null);
}
//Initialization of Adapter and ListView and hooking them together
RateAdapter rateAdapter = new RateAdapter(this , titlesArray);
Now, inside adapter class, Handle the Event for radio buttons. To pass data back to Activity, created an interface to update respective index.
interface RadioClickListener{
void radioClicked(int position, int rate);
}
...
RadioClickListener radioClickListener;
...
public RateAdapter(Context context, ArrayList<String> arrayList) {
super(context, 0, arrayList);
this.context = context;
radioClicked = (RadioClickListener) context;
}
So, when you click the ratioButton, item at respective index is updated by calling
//pass the position and rate for that item
radioClickListener.radioClicked(position, "1");
And finally implement the interface to the Activity to update the List.
public class TempActivity extends AppCompatActivity implements RateAdapter.RadioClickListener {
...
#Override
public void radioClicked(int position, int rate){
rates.get(position).setRate(rate);
}
Now, you have the updated rates List, So to pass it to another activity parcel is with the intent and send it.

Parse Html from website with android studio, Java

I am making this question today because I can not find certain information on google and/or Stack Overflow. My Problem is, I am creating a Android Application and I want certain information from a Website. So I use Jsoup as my parse Library. I follow all the instruction and set The data in the Text to Show up with The HTML text. For Some reason it is either a network connection or my code is wrong in communicating with the website? I do not know what is up with the app. I am Using Android Studio, so when running either the emulator or on a device it will just not pull html from the website.
Here is My code for 2 Classes. This has to be in Java.
package update.app.jdog1218.com.messingaround;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends Activity {
private Button answer_Button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout bible = new RelativeLayout(this);
}
#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.
return super.onOptionsItemSelected(item);
}
public void gotoInbeddedBible(MenuItem item) {
Intent bibleclass = new Intent(this, bible.class);
final int result = 1;
bibleclass.putExtra("callingActivity", "MainActivity");
startActivity(bibleclass);
startActivityForResult(bibleclass, result);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
public void exit(MenuItem item) {
Button exitProcess = (Button) findViewById(R.id.submit);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
public void sotd(MenuItem item) {
Intent clickedSotd = new Intent(this, Sotd.class);
int result = 1;
startActivity(clickedSotd);
}
}
This is the class I want to use Jsoup in.
package update.app.jdog1218.com.messingaround;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.Menu;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import java.io.IOException;
import static org.jsoup.Jsoup.*;
/*
* Created by Joel on 5/28/2015.
*/
public class Sotd extends Activity {
#Override
protected void onStart() {
super.onStart();
}
String title;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.sotd);
Intent activityThatCalled = getIntent();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
/**
* Pull and Parse the HTML of Compass HB for SOTD.
*
* #return DocumentString
* #throws IOException
*/
protected String pullHTML() {
super.onStart();
final String url = "https://www.compasshb.com/api/v1/passages";
Document doc = null;
TextView textView = (TextView) findViewById(R.id.SOTD);
try {
doc = Jsoup.connect(url).get();
textView.setText(doc.ownText());
String paragraph = doc.title();
return paragraph;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostResume() {
super.onPostResume();
}
}
This is the XML File for the Layout I want to output too.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:weightSum="1"
android:background="#drawable/the_rendered_background">
<TextView
android:text="#string/text_of_activity_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="40dp"
android:capitalize="none"
android:width="200dp"
android:textColor="#000000"
android:id="#+id/text_view" />
</LinearLayout>
SOTD is where I want it to output too.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Sotd"
android:weightSum="1"
android:background="#drawable/the_rendered_background"
android:backgroundTintMode="add">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/SOTD"
/>
</LinearLayout>
Pretty Much I just need someone to tell me what I am doing wrong./Review

I am working on a basic toDo app. When I long press on the item it should be deleted from my list but it does nothing. What am i doing wrong?

I am trying to add and delete items in my todo list. It adds the items fine but I have set up a onLongClickListener for deleting the items and it does nothing. I am a beginner so I may have missed something. Please help me out. Any help is appreciated.
package com.example.todolist;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.os.Build;
import android.app.ListActivity;
public class MainActivity extends Activity implements OnClickListener{
private ArrayList<String> items;
private ArrayAdapter <String> adapter;
private EditText ptadd;
private Button badd;
private ListView lvTodo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
items = new ArrayList <String>();
adapter = new ArrayAdapter<String>(this,adroid.R.layout.simple_list_item_1, items);
lvTodo.setAdapter(adapter);
setListViewListener();
}
private void setListViewListener(){
lvTodo.setOnItemLongClickListener(new OnItemLongClickListener (){
#Override
public boolean onItemLongClick(AdapterView<?> vadapter, View item,
int position, long id) {
// TODO Auto-generated method stub
items.remove(position);
adapter.notifyDataSetChanged();
return true;
}
});;
}
private void initialize() {
// TODO Auto-generated method stub
ptadd = (EditText) findViewById(R.id.etadd);
lvTodo = (ListView) findViewById(R.id.lvTodo);
badd = (Button) findViewById(R.id.badd);
badd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String lv = ptadd.getText().toString();
adapter.add(lv);
ptadd.setText("");
}
}
my XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
>
<ListView
android:id="#+id/lvTodo"
android:layout_width="293sp"
android:layout_height="250sp" >
</ListView>
<EditText
android:id="#+id/etadd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/button1"
android:layout_weight="70"
android:ems="10"
/>
<Button
android:id="#+id/badd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="30"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Add"
/>
</RelativeLayout>
In the code you posted, you're never calling setListViewListener. Call the method in initialize
private void initialize() {
// TODO Auto-generated method stub
ptadd = (EditText) findViewById(R.id.etadd);
lvTodo = (ListView) findViewById(R.id.lvTodo);
badd = (Button) findViewById(R.id.badd);
badd.setOnClickListener(this);
//Missing this
setListViewListener();
}

Application stopped working when loading layout with setContentView

Here's the XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/search_lyt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:name="search_act"
tools:context="com.example.app.Hisp$PlaceholderFragment">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/hispania_lgs"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/back2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Info"
android:id="#+id/info2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/model_list"
android:layout_below="#+id/textViewML"
android:layout_alignParentRight="true"
android:layout_above="#+id/back2"
android:choiceMode="singleChoice" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select any of the models below and press Info for the model's specifications"
android:id="#+id/textViewML"
android:layout_below="#+id/imageView2"
android:layout_alignLeft="#+id/model_list" />
And using the setContentView method results in an 'Application stopped working'.
setContentView(R.layout.search_hisp);
Any idea on how to fix this? I'm quite new to Android Development and still trying to find how to switch layouts the correct way.
Well, even I change the onCreate()' setContentView to R.layout.search_hisp and gave me the error on startup. So my guess is it's probably from the XML file or something.
Thanks in advance!
Edit, there's the error:
>
03-25 12:10:23.415 20858-20858/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
at com.example.app.Hisp.beginSearch(Hisp.java:121)
at com.example.app.Hisp$3.onClick(Hisp.java:107)
at android.view.View.performClick(View.java:4231)
at android.view.View$PerformClick.run(View.java:17537)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ Application Label: Hisp_Selector
And here's the code:
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.preference.DialogPreference;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.ViewGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.widget.LinearLayout;
public class Hisp extends ActionBarActivity {
public static ActionBarActivity activity;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
activity = this;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_hisp);
TextView txt = (TextView) findViewById(R.id.textViewML);
Button btn = (Button) g(R.id.search);
Button rst = (Button) g(R.id.reset);
rst.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
finish();
startActivity(getIntent());
}
});
OnClickListener _rdb = new OnClickListener() {
#Override
public void onClick(View view) {
((CheckBox) g(R.id.R134a)).setChecked(false);
((CheckBox) g(R.id.R22)).setChecked(false);
((CheckBox) g(R.id.R404A)).setChecked(false);
((CheckBox) g(R.id.R507A)).setChecked(false);
((CheckBox) view).setChecked(true);
}
};
((CheckBox) g(R.id.R134a)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R22)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R404A)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R507A)).setOnClickListener(_rdb);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
beginSearch();
}
});
/*
if (stanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
*/
}
public void beginSearch() {
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Boolean err = false;
try {
if (!(Double.parseDouble((((EditText) g(R.id.capacity)).getText().toString().trim())) >= 0 &&
isBetween(-35, 5, Integer.parseInt(((EditText) g(R.id.evaptemp)).getText().toString().trim())) &&
isBetween(28, 58, Integer.parseInt(((EditText) g(R.id.condtemp)).getText().toString().trim())) &&
isBetween(5, 13, Integer.parseInt(((EditText) g(R.id.dt1)).getText().toString().trim()))
)) err = true;
} catch(Exception e) {
err = true;
}
if (err) {
showMessageBox("ERROR", "Make sure you have filled all the fields correctly.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
setContentView(R.layout.search_hisp);
}
}
public View g(int id) {
return activity.findViewById(id);
}
public Boolean isBetween(Integer i1, Integer i2, Integer ix) {
if (ix >= i1 && ix <= i2) return true;
return false;
}
public void showMessageBox(Object ttl, Object msg, DialogInterface.OnClickListener rt) {
new AlertDialog.Builder(activity)
.setMessage(msg.toString())
.setTitle(ttl.toString())
.setCancelable(false)
.setNeutralButton(android.R.string.ok, rt)
.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.hisp, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hisp, container, false);
return rootView;
}
}
}
Because in onCreate() you have used
EditText textViewML = (EditText) findViewById(R.id.textViewML);
instead of
TextView txt = (TextView) findViewById(R.id.textViewML);
so you got problem. So you need to use after your setContentView() method.
TextView txt = (TextView) findViewById(R.id.textViewML);
Put in the onCreate :
TextView textViewML = (TextView) findViewById(R.id.textViewML);
The error was from
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Thanks a lot guys for pointing this out!
you are casting Textview to EditText dont do that
EditText textViewML = (EditText) findViewById(R.id.textViewML);
change it as
TextView textViewML = (TextView) findViewById(R.id.textViewML);
Exception is not your layout file it is in your java file you are casting TextView into EditText.
You can not Cast Super class in to sub class.
you can cast Sub class into Super Class.
You can Cast EditText into TextView but not TextView in to EditText.
Change this line
TextView txt = (TextView) findViewById(R.id.textViewML);
Thanx

How do you make a list view clickable

I am trying to get this right, but this is getting me good. I have an example but i don't know how it is working.
I got this much done.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/welcome" />
</RelativeLayout>
now I think my problem is in this java file. The getListView thing is kicking me around. I think this is the answer but i just don't know how to get this right.
I think i know how to get it to work later.
package com.example.boonehallfrightnightsapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final String[] CHOICES = new String[]
{
"Main House",
"Nightmare",
"Zombie Town",
"Hayride",
"Quit"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//found this part on an example
//Set up ArrayAdaptor for the options
setListAdapter(new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
#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;
}
private void setListClickListener()
{
//Set up the click listener for the options
getListView().setOnItemClickListener
(
new OnItemClickListener()
{
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0: finish();
break;
case 1: finish();
break;
case 2: finish();
break;
case 3: finish();
break;
case 4: finish();
break;
default: break;
}
}
}//END OnItemClickListener
);//END setOnItemClickListener
}//END setListClickListener
}
You should extend ListActivity to call getListView() to get the ListView from the layout. You can check the documentation here - http://developer.android.com/reference/android/app/ListActivity.html (Class Overview > Screen Layout)

Categories

Resources