So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#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.action_settings) {
return true;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.
Related
Im developing a contacts app, and for now Ive been trying to get this drawables from the array get uploaded into the Gridview on the main screen AFTER the save mosaic button is clicked in the mosaic creation screen.
the floating action button (red plus button) on the mosaicListScreen (main screen) leads to the MosaicCreationScreen). the user hypothetically uploads the image and enters the mosaic name then saves using the save mosaic button, as can be seen in the image here
For now, before I focus on uploading image and letting the user create their own unique mosaics (groups), Im testing the Gridview updating with some drawables, which are listed in the array as can be seen in the code below.
The issue thats occuring is as soon as the user clicks the floating action button on the main screen, it updates the gridview with the drawables listed in the array of the MosaicCreation Screen, THEN it goes to the MosaicCreationScreen, and when save mosaic button is clicked on the MosaicCreationScreen, the intent goes to the main screen as its supposed to do, except the gridview will have nothing on it.
so its like its doing the opposite of whats supposed to happen in steps.
here is my code for the two screens:
public class mosaicsListScreen extends AppCompatActivity {
public static mosaicsListScreen theScreen; //this variable is used in the MosaicCreationScreen to point to this screen to find the GridView by id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = this;
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
}
}
here is the code for the MosaicCreationScreen (the one that opens after user clicks floating action button from mosaicListScreen (main screen))
public class MosaicCreationScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaic_creation_screen);
final GridView mosaicList = (GridView) mosaicsListScreen.theScreen.findViewById(R.id.mosaicList);
mosaicList.setAdapter(new ImageAdapter(this)); //this line of code displays the mosaics on mosaicListScreen
Button saveNewMosaicButton = (Button) findViewById(R.id.saveNewMosaicButton);
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
//mThumbIds.notify();
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
startActivity(intent);
finish();
//mosaicList.setAdapter(new ImageAdapter(this)); //this displays the mosaics on mosaicListScreen, it logically should go here, however "this" causes an error saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)
Toast.makeText(mosaicsListScreen.theScreen, "Mosaic Created!", Toast.LENGTH_SHORT).show();
}
});
/* mosaicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mosaicsListScreen.theScreen, "", Toast.LENGTH_SHORT).show();
}
});*/
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
//this array holds the drawables that would appear on the Gridview
private Integer[] mThumbIds = {
R.drawable.family,
R.drawable.project
};
}
}
Here are the XML for the layouts:
content_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<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="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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="codesages.mosaic.mosaicsListScreen"
tools:showIn="#layout/activity_mosaics_list_screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/create_a_mosaic_or_pick_from_the_mosaics_created"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deleteMosaicButton"
android:src="#android:drawable/ic_menu_delete"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:contentDescription="" />
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/mosaicList"
android:layout_above="#+id/textView7"
android:numColumns="auto_fit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/holdMosaictoDeleteLabel"
android:id="#+id/textView7"
android:layout_marginBottom="16dp"
android:layout_above="#+id/deleteMosaicButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="codesages.mosaic.mosaicsListScreen">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/createMosaicButton"
android:layout_width="56dp"
android:layout_height="66dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
<include layout="#layout/content_mosaics_list_screen" />
</android.support.design.widget.CoordinatorLayout>
activity_mosaic_creation_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<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="codesages.mosaic.MosaicCreationScreen"
android:focusable="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mosaicNametextField"
android:hint="Mosaic Name"
android:layout_marginTop="81dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save New Mosaic"
android:id="#+id/saveNewMosaicButton"
android:layout_marginTop="48dp"
android:layout_below="#+id/uploadMosaicImageButton"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Mosaic Image"
android:id="#+id/uploadMosaicImageButton"
android:layout_marginTop="68dp"
android:layout_below="#+id/mosaicNametextField"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
mosaicList.setAdapter(new ImageAdapter(this));
thats what appears to be creating the mosaics. if i comment this out, i wont see anything in the gridview.
however, i believe that should be inside the saveNewMosaicButton onClick, but I am getting an error that says "saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)"
HERE is an image example of what the desired result should be. however whats happening right now is as ive stated, as soon as the floating action button is clicked, the mosaics are created, THEN it takes you to the creation screen, in which wehn i click save mosaics, it actually erases the mosaics...a job of the trash icon which is too soon to function for now heh.
appreciate help on this
Currently, you have
public static mosaicsListScreen theScreen;
in your first Activity which you use to fill the ListView in this first Activity. This is a dangerous approach because the Activity instance referenced by this variable may be destroyed, for example if you're doing work in your second Activity (e.g. downloading images) which uses much memory, but also if the user somehow triggers a configuration change.
As you are calling finish() after starting the second Activity, you even tell the system that the first Activity may be destroyed. The only reason you did not get a NPE is that the system destroys the finished Activity not instantly but as soon as it seems a good idea to do so.
All in all, you need a way to safely transmit information from one Activity to the other. In your case, I think you would like to send the Uri of the selected images ( or for now, send the resource id of the selected drawables). Both can be accomplished by using Intent extras.
Basically, there are two options:
use startActivityForResult() and override onActivityResult() to obtain the desired information for the first Activity
simply start the first Activity from the second Activity once you have the result and use getIntent() in the first Activity (e.g. in onCreate()) to check for results
No matter what you do, always access UI elements like the ListView in the Activity to which they belong!
If you choose the second option, your first Activity could look like this:
public class mosaicsListScreen extends AppCompatActivity {
public static final String THUMB_IDS = "someuniquestring";
private GridView mosaicList;
private ArrayList<Integer> mThumbIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
fillThumbIds();
mosaicList = (GridView) findViewById(R.id.mosaicList);
// Note: Adapter code in this Activity
mosaicList.setAdapter(new ImageAdapter(this));
}
private void fillThumbIds()
{
mThumbIds = new ArrayList();
// somehow get older thumb ids if necessary (from database?)
// and add to ArrayList like this:
mThumbIds.add(R.drawable.family);
mThumbIds.add(R.drawable.project);
// assuming we transmit resource id's: use an int array with the Intent
int[] newThumbIds = getIntent().getIntArrayExtra(THUMB_IDS);
if (newThumbIds != null)
{
// loop through the array to add new thumb ids
for (int i = 0; i < newThumbIds.length; i++) {
mThumbIds.add(newThumbIds[i]);
}
}
}
// Adapter code goes here
// Note: thumbIds no longer as array but as ArrayList!
}
In the second Activity, you put the selected thumb ids as Intent extra as follows:
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
// if 'myNewThumbs' is the int array with the new thumb ids
intent.putExtra(mosaicsListScreen.THUMB_IDS, myNewThumbs);
startActivity(intent);
finish();
}
});
I took some code to make a simple Form on Android. It seems as if some parts of the code are referencing to something. I'm not sure what to put there to make it work? I get errors.
Error:(18, 32) error: cannot find symbol variable activity_form
Error:(33, 88) error: package com.chalkstreet.learnandroid.main does not exist
Error:(48, 50) error: cannot find symbol class MainSource
Error:(57, 41) error: cannot find symbol variable menu_main
I don't think that I need to be using the package that I am not having.
Example problem:
Intent sender = new Intent(Form.this,
===> ???? com.chalkstreet.learnandroid.main.Display.class);
Here's my form:
public class Form extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initialize buttons and Edit Texts for form
Button btnSubmit = (Button) findViewById(R.id.button_submit);
Button btnSrc = (Button) findViewById(R.id.buttonSrc);
final EditText name = (EditText) findViewById(R.id.editText1);
final EditText email = (EditText) findViewById(R.id.editText2);
final EditText phone = (EditText) findViewById(R.id.editText4);
//Listener on Submit button
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sender = new Intent(Form.this, com.chalkstreet.learnandroid.main.Display.class);
Bundle b1 = new Bundle(); //Bundle to wrap all data
b1.putString("name", name.getText().toString()); //Adding data to bundle
b1.putString("email", email.getText().toString());
b1.putString("phone", phone.getText().toString());
sender.putExtras(b1); //putExtras method to send the bundle
startActivity(sender);
Form.this.finish(); //Finish form activity to remove it from stack
}
});
//Listener on source button
btnSrc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(Form.this, MainSource.class);
startActivity(j);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Form.this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks
Create a file called MainSource.java, that is if you haven't done so already, and create a file called menu_main.xml in the menu folder under the res directory and add your menu items, create another layout file in the layout folder under the res directory and name it activity_form.xml, you can then add the necessary views with the ids matching those in Form.java
More illustratively, menu_main might contain
<menu 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">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
activity_form.xml could possibly be something like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email" />
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Something Else" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonSrc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
I have no idea what you want MainSource to do so I can't say much about that. I hope this helps.
When you create an explicit Intent, you only need to provide the starting context and the ending class.
Intent i = new Intent(FirstActivity.this, ResultActivity.class);
Hello i need Your help in displaying data from database in activity, ive been trying many things but have no idea how to do that. Im creating some kind of weather app. It has Data in Database on the device.
There is DataBaseHandler Class which returns List with all Spots.
public List<Spot> getUserSpotList(int id){
List<Spot> spotList = new ArrayList<Spot>();
String selectQuery = "SELECT " +SPOT_ID+","+ SPOT_NAME + ","+ SPOT_LATITUDE + ","+SPOT_LONGITUDE+","+SPOT_WIND_SPEED +","+SPOT_WEATHER_ICON+
" FROM " + TABLE_SPOT + " WHERE "+SPOT_USER_ID + "="+id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Spot spot = new Spot();
spot.setSpot_id(Integer.parseInt(cursor.getString(0)));
spot.setSpotName(cursor.getString(1));
spot.setSpotLatitude(cursor.getString(2));
spot.setSpotLongitude(cursor.getString(3));
spot.setWindSpeed(Double.parseDouble(cursor.getString(4)));
spot.setSpotWeatherIcon(cursor.getString(5));
// Adding User to list
spotList.add(spot);
} while (cursor.moveToNext());
}
return spotList;
}
And i Have Activity with listView xml in witch i want to display some stuff from the code above based on another relativelayout for one element.
SpotActivity.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: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="com.example.mk.rcwindy.SpotActivity">
<ListView
android:id="#+id/listLajout"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:layout_weight="1"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And here is Relative layout for one element in the list view above.
I would like to connect SpotName from database with TextView id=SpotName, Windspeed from database with Windspeed Text View, and Display image in ImageView based on SpotWeatherIcon from database.
spotlista_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:id="#android:id/list">
<ImageView
android:id="#+id/SpotAvilabilityIcon"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="#color/green_apple"/>
<ImageView
android:id="#+id/WeatherIcon"
android:layout_width="70dp"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/WindSpeed"
android:scaleType="centerInside"
/>
<TextView
android:id="#+id/WindSpeed"
android:text=""
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/WindSpeedUnit"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
<TextView
android:text="m/s"
android:textSize="30dp"
android:id="#+id/WindSpeedUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/SpotAvilabilityIcon"
android:layout_toStartOf="#+id/WeatherIcon"
android:layout_toLeftOf="#+id/WeatherIcon"
android:layout_centerVertical="true">
<TextView
android:id="#+id/SpotName"
android:text=""
android:textSize="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
</FrameLayout>
</RelativeLayout>
And here is the code of activity SpotActivity
public class SpotActivity extends ActionBarActivity {
int loggedUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot);
Intent intent = getIntent();
if (null != intent) {
loggedUserId = intent.getIntExtra("logged", 0);
}
String text = "logged user id = "+loggedUserId;
Toast t1 = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
t1.show();
}
public int userIdSender(){
return loggedUserId;
}
#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_spot, 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;
}
if (id== R.id.action_new){
Intent intent = new Intent(this, SpotAddActivity.class);
intent.putExtra("logged",loggedUserId);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Thanks for Help! I tried to do that and still have a big problems so now im asking for help. Its a school project im working at and that is the last thing i have to do to make the app work-Display stuff :D
You need to create an adapter for your ListView. I recommend you watch The World Of ListView.
All an adapter does is provide a view for each item in your data set. For cursor data, you should subclass CursorAdapter and implement the newView() and bindView() methods at the minimum.
I have an app which inflates button views on a click of a button(Button A). The button views inflated work properly, executing the code in their onClick method.
Now to save the layout generated, I keep a count of number of times the Button A is clicked and save this value using SharedPreferences. In onCreate method I create a for loop for the number of times the Button A was clicked and re-inflate those buttons, thus generating the same layout that was on screen when the app was killed. Though now, the buttons generated in the onCreate method no longer function.
I hope I have made some sense. The problem, when the app is started again in future, it builds the layout as it was when the app was clicked, but the button views no longer function for the onCLick method.
Here's the code for reference:
MainActivity.java
public class MainActivity extends Activity {
EditText et;
String z, r;
LinearLayout ll;
SharedPreferences sp;
Button fb1;
int c=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText) findViewById(R.id.et);
sp=getSharedPreferences("MY_PREFS", 0);
if (sp.contains("counter")) {
for (int i=1;i<=sp.getInt("counter", 1);i++) {
cr();}
}
c=sp.getInt("counter", 0);
}
public void cr() {
ll=(LinearLayout) findViewById(R.id.ll);
LayoutInflater li=getLayoutInflater();
View vw=li.inflate(R.layout.infla, null);
ll.addView(vw);
fb1=(Button) vw.findViewById(R.id.btn);
fb1.setId(c);
}
public void click(View v) {
int z=v.getId();
switch (z) {
case (R.id.button):
et=(EditText) findViewById(R.id.et);
cr();
et.setText("");
c=c+1;
break;
}
Editor e=sp.edit();
//e.putString("check", r);
e.putInt("counter", c);
//e.putInt("id", c);
e.commit();
for (int i=0; i<=c;i++){
if (z%2==0) {//Present
et.setText("Present");}
else if(z%2==1)
et.setText("Absent");
}
}
#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;
}
}
activity_main.xml
<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:id="#+id/ll"
tools:context=".MainActivity" >
<EditText
android:id="#+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:ems="10"
android:hint="Enter something" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:onClick="click"
android:text="Click" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="remove" />
</LinearLayout>
infla.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="click" />
</LinearLayout>
Edit:
You seem to have assigned redundant id's to the button during initialization.Each button would be assigned the value 'c' instead of 0 to 'c'.
Additionally It seems only logical to create click listeners on the fly as well ,since you are inflating button on the go.Try implementing the onclicklistener instead of the hardwired click() method in the xml.
i.e
public void cr() {
ll=(LinearLayout) findViewById(R.id.ll);
LayoutInflater li=getLayoutInflater();
View vw=li.inflate(R.layout.infla, null);
ll.addView(vw);
fb1=(Button) vw.findViewById(R.id.btn);
fb1.setId(c);
fb1.setOnClickListener(new View.OnClickListener(){
//Stuff you wish to do on click
});
}
I a new to Android development, so this is kind of a basic question.
I would like to implement the same behavior as in the Contacts app. You have a ListView with a series of Contacts | phone icons. There you have one behavior when you click on the contact name, and another behavior when you click on the phone icon.
Here is my code.
Any help is much appreciated.
In summary, what is wrong with the approach
switch (v.getId()) {
case R.id.imageButtonAction:
Activity Class
public class CompaniesActivity extends Activity {
MyApp app;
ListView listCompanies;
Cursor cursor;
// Adapter and its corresponding FROM and TO statements. The number and sequence of the arguments must match in FROM / TO arguments.
SimpleCursorAdapter adapter;
static final String[] FROM = { MenuNavigationData.C_COMPANY, MenuNavigationData.C_DESCRIPTION};
static final int[] TO = { R.id.textCompany, R.id.textDescription }; //
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companies);
//Gets a reference to the application
app = (MyApp) getApplication();
// Find your views
listCompanies = (ListView) findViewById(R.id.listCompanies);
addButton = (Button) findViewById(R.id.buttonAdd);
// Add actions to user interaction
listCompanies.setOnItemClickListener(new OnItemClickListener() {
#Override
**public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
switch (v.getId()) {
case R.id.imageButtonAction:
startActivity(new Intent(app, InstructionsActivity.class));
break;
default:
int i = adapter.getItemViewType(position);
startActivity(new Intent(app, EditMenuNavigationActivity.class));
break;
}**
}
});
}
Activity xml
<!-- Companies ListView-->
<ListView android:id="#+id/listView1" android:layout_height="wrap_content" android:layout_width="match_parent"></ListView>
<ListView
android:id="#+id/listCompanies"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#5555"/>
</LinearLayout>
Row xml
android:background="#ffff"
android:padding="6dip">
<!-- Company TextView -->
<TextView
android:id="#+id/textCompany"
android:text="TIM"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:singleLine="true"
android:ellipsize="marquee"
android:textColor="#c000"
android:textStyle="bold"
android:textSize="25sp"/>
<!-- Description TextView -->
<TextView
android:id="#+id/textDescription"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_below="#id/textCompany"
android:layout_alignWithParentIfMissing="true"
android:layout_alignParentLeft="true"
android:singleLine="true"
android:ellipsize="marquee"
android:textColor="#c000"></TextView>
<!-- Action ImageView -->
<ImageView
android:id="#+id/imageButtonAction"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:background="#drawable/icon"/>
</RelativeLayout>
Your onItemClick() callback receives both the specific view as well as its position (0-based), each of these can help you decide which view was clicked. The position is an index into the items you've added, and for more complicated scenarios you can view.setTag(Object o), and use getTag() to retrieve it from your callback.
New much better approach to solve this issue elegantly, and with less code!!!
With the following modifications, the User interface is much more responsive, no more double-clicking issues. :)
Much, much less code that simply works!
Modifications to Row xml
Insert a Linear layout to wrap both the
In this Linear layout, insert a tag named android:onClick="editCompanyClick"
This is the click handler that will be called in the Activity.
Insert a Linear layout to wrap the
In this Linear layout, insert a tag named android:onClick="dialClick"
This is the click handler that will be called in the Activity.
Modifications to Activity class
Remove the previous code
listCompanies.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView arg0, View v, int position, long id) {
TextView company = (TextView) v.findViewById(R.id.textCompany);
ImageView dial = (ImageView) v.findViewById(R.id.imageButtonDTMFDial);
company.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(app, EditMenuNavigationActivity.class));
}
});
dial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(app, InstructionsActivity.class));
}
});
}
Insert the code
public void dialClick(View v) {
startActivity(new Intent(app, InstructionsActivity.class));
}
public void editCompanyClick(View v) {
startActivity(new Intent(app, EditMenuNavigationActivity.class));
record
}
Row xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:onClick="editCompanyClick"
android:layout_weight="1">
<!-- Company TextView -->
<TextView android:singleLine="true" android:text="TIM" android:id="#+id/textCompany" android:ellipsize="marquee" android:layout_height="wrap_content" style="#android:style/TextAppearance.Medium" android:layout_width="match_parent" android:gravity="top"></TextView>
<!-- Description TextView -->
<TextView android:singleLine="true" android:text="Chamar atendente" android:id="#+id/textDescription" android:ellipsize="marquee" android:layout_height="wrap_content" style="#android:style/TextAppearance.Small" android:layout_width="match_parent" android:gravity="bottom"></TextView>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:id="#+id/linearLayout2"
android:onClick="dialClick"
android:layout_width="wrap_content" android:layout_gravity="right">
<!-- DTMFDial ImageView -->
<ImageView android:layout_height="wrap_content" android:background="#drawable/icon" android:id="#+id/imageButtonDTMFDial" android:layout_gravity="right" android:layout_width="wrap_content"></ImageView>
</LinearLayout>
</LinearLayout>
I finally found a solution.
This solves the issue. But adds another one. As expected, the ListView now behaves differently when the user clicks on different views(either TextView or ImageView).
But it seems unresponsive. I have to "double-click" in order to trigger either the company.setOnClick or dial.setOnClick. Any suggestions?
// Add actions to user interaction
listCompanies.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
TextView company = (TextView) v.findViewById(R.id.textCompany);
ImageView dial = (ImageView) v.findViewById(R.id.imageButtonDTMFDial);
company.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(app, EditMenuNavigationActivity.class));
}
});
dial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(app, InstructionsActivity.class));
}
});
}