How to start an activity on button press in ListView - java

I've done some research but I've found myself getting quite confused on the topic of ListViews and creating a button within a ListView.
For my project, I have a ListView created in one layout.xml (called recap_page.xml) and in another layout.xml (row_layout.xml) I have the layout view (the layout on row_layout.xml is what is displayed on recap page)
The rows are populated with data entered by the user in another activity using SQLiteDatabase (DataEntryHome.java) (not relevant for this, but I'm just giving some context)
Basically, what I want to do is to have the button in each row open a new activity. As it stands, when I press the button, the app crashes. I believe I have to use a method that links to the button by using onClick. I have tried this by creating a method called viewOrder although I'm not sure which activity I have to put the method in because I've confused myself by creating different activities for different purposes.
Is anyone able to help me and explain:
a) What steps I have to take to make these buttons responsive?
b) What activities do I need to implement them into?
My code
recap_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_view"
android:textColor="#000000"
android:clickable="true">
</ListView>
</RelativeLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#30609d">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/firstNameText"
android:text="First name here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/surnameText"
android:text="Surname here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/emailText"
android:text="Email here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/phoneText"
android:text="Phone here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/addInfoText"
android:text="Additional info"
android:gravity="center"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="53dp"
android:layout_height="37dp"
android:text="GO"
android:id="#+id/goButton"
android:onClick="viewOrder"
android:layout_marginTop="7dp"/>
</LinearLayout>
</ScrollView>
RecapPage.java
package com.example.joe.printedclothing;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecapPage extends AppCompatActivity{
String classNames[] = {"HomeActivity", "SelectDesign"};
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
}
ListDataAdapter.java
package com.example.joe.printedclothing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler {
TextView FIRSTNAME, SURNAME, EMAIL, PHONE, ADDINFO;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
return row;
}
}
And I don't know why, but here's my home activity:
package com.example.joe.printedclothing;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
public class HomeActivity extends AppCompatActivity {
private static Button StagHenButton, ReviewOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
StagHenButton = (Button) findViewById(R.id.StagHen); // Locates the button that the user presses to move to the next activity
StagHenButton.setOnClickListener( // When the button is clicked...create an intent to move to next activity
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent("com.example.joe.printedclothing.SelectDesign"); // Intent to choose next activity
startActivity(newIntent);
}
}
);
}
public void addContact (View view) {
Intent intent = new Intent(this,DataEntryHome.class);
startActivity(intent);
}
public void viewContact (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
public void viewOrder (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
#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_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

You can set the OnClickListener in the Adapter.getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
layoutHandler.goButton = (Button) row.findViewById(R.id.goButton);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
layoutHandler.goButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//Start your activity here
}
}
);
return row;
}

Just put the below code in your function from where you want to launch new Activity.This is the tested code.It might be helpful for you
Intent i=new Intent(getContext(),Main2Activity.class);
getContext().startActivity(i);

Related

How to pass edit text value from adapter to activity?

I have a recycler view adapter which takes input from user in edittext. I want to pass those values as a list back to the activity in which the recycler view is present.
I need this list in activity to send as a parameter to api through retrofit.
Create an interface like this:
interface IList {
void addToList(String editTextValue);
}
Implement this interface in your Activity:
class MainActivity extends AppCompatActivity implements IList {
#Override
public void addToList(String editTextValue) {
//TODO("logic for adding to list and sending")
}
}
Add to Adapter's constructor Activity, that implementing IList interface, as paramert:
public Adapter(IList listener){
this.listener = listener;
}
Execute addToList method in your adapter:
#Override
public void onBindViewHolder(NewViewHolder holder, int position) {
holder.sendButton.setOnClickListener .setOnClickListener(v -> {
String newText = holder.editText.text.toString()
listener.addToList(newText)
});
}
There's a working sample.
MainActivity.java
```
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Adapter adapter = new Adapter();
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setAdapter(adapter);
EditText editText = findViewById(R.id.editText);
editText.setOnEditorActionListener((textView, actionId, keyEvent) -> {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// add item
adapter.addItem(editText.getText().toString());
// clear text input
textView.setText("");
handled = true;
}
return handled;
});
}
}
```
activity_main.xml
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Insert text.."
android:imeOptions="actionDone"
android:inputType="text"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintVertical_chainStyle="packed" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Adapter.java
```
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<String> items = new ArrayList<>();
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(android.R.layout.test_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
String currentItem = items.get(position);
holder.textView.setText(currentItem);
}
public void addItem(String item) {
// add at first position - replace with your desired index
int index = 0;
this.items.add(index, item);
notifyItemInserted(index);
}
#Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
protected TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
}
You can use the "done" key on the keyboard to notify the adapter that an item has been added.
To display the "done" button in the xml it is necessary to use these two instructions in the edittext
android:imeOptions="actionDone"
android:inputType="text"

How to use viewHolder to make listView user input not go back to default when scrolling off screen

I have a listView where a user can enter input to change the textView on each listView row. When you scroll the row off the screen the edited text goes away and the default text reappears. I know this is fixed with the viewHolder but I can't get it to work in my custom adapter class.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> Chores = new ArrayList<>();
//Chores.add("");
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Chores.add("");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.emilythacker.chorelist.R.id.textView_ID;
class CustomAdapter extends ArrayAdapter{
ArrayList<String> choreText;
public CustomAdapter(Context context, ArrayList choreText) {
super(context, R.layout.custon_listview_row, choreText);
this.choreText = choreText;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//final TextView textView = (TextView) customView.findViewById(textView_ID);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.custon_listview_row, null);
holder = new ViewHolder();
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imageButton_ID);
holder.textView = (TextView) convertView.findViewById(textView_ID);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(choreText.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//what happens when textView is clicked
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
final EditText input = new EditText(getContext());
input.setHint("hint");
alertDialog.setView(input);
alertDialog.setTitle("Set Chore");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
holder.textView.setText(input.getText().toString());
dialog.dismiss();
}
});
alertDialog.show();
}
});
holder.imageButton.setImageResource(R.drawable.clock);
return convertView;
}
static class ViewHolder {
ImageButton imageButton;
TextView textView;
}
}
activity_main.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:id="#+id/activity_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"
tools:context="com.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
custon_listview_row.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"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<TextView
android:text="Click here to add chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/textView_ID"
android:textSize="25dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/imageButton_ID"
android:layout_marginEnd="11dp"
/>
</RelativeLayout>
When text is entered into the edit text, you need to save it to a variable associated with that position, and in getView you need to set the text of the editText to that position's value. Otherwise you'll just have whatever random value was in there last.
Basically, any value that can change in a row's UI must be saved and written to it in getView.

How to get value of a row in listview in android

I am new in android
The structure of my application consist of:
activity_main.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="com.example.reyhane.myapplication.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
cell.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layoutDirection="rtl">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/nationalCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:text="حذف" />
</TableRow>
</TableLayout>
MainActivity.java
package com.example.reyhane.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
public ListView list;
public ArrayList<Person> countries = new ArrayList<Person>();
public ListAdapter adapter;
public void fillPerson(String nationalCode) {
Person person = new Person();
person.setNationalCode(nationalCode);
person.setName("reza");
person.setLastName("hghgh");
person.setPhone("231345");
countries.add(person);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
fillPerson("6768767");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Object o = list.getItemAtPosition(position);
Person person = (Person) o;
openAddPersonActivity(person.getNationalCode());
}
});
}
public void openAddPersonActivity(String nationalCode) {
Intent i = new Intent(MainActivity.this, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
}
ListAdapter.java
package com.example.reyhane.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* Created by reyhane on 11/24/16.
*/
public class ListAdapter extends BaseAdapter {
MainActivity mainActivity;
ListAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public int getCount() {
return mainActivity.countries.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolderItem {
TextView nationalCode;
TextView name;
TextView lastName;
TextView phone;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.nationalCode = (TextView) convertView.findViewById(R.id.nationalCode);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolderItem) convertView.getTag();
}
Button deleteBtn = (Button) convertView.findViewById(R.id.delete_btn);
holder.nationalCode.setText(this.mainActivity.countries.get(position).getNationalCode());
holder.name.setText(this.mainActivity.countries.get(position).getName());
holder.lastName.setText(this.mainActivity.countries.get(position).getLastName());
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
mainActivity.countries.remove(position); //or some other task
notifyDataSetChanged();
}
});
return convertView;
}
}
My problem:
As you see in my application, i have list of person in listview.
In this form i add person and delete and edit it.
I can remove each record of listview but i can not get nationalCode value of person of each reacord in listview to fetch person from database by this nationalcode and edit it.
How do i do?
please help me
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
{
String nationalcode = (String) ((TextView) v.findViewById(R.id.nationalcode)).getText();
Toast.makeText(getApplicationContext(), "NATIONAL CODE "+nationalcode, Toast.LENGTH_SHORT).show();
openAddPersonActivity(nationalcode);
}
});
Hope it helps.
try this :
openAddPersonActivity(countries.get(position).getNationalCode());
FYI, the list.setOnItemClick doesn't work
add this into your ListAdapter:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mainActivity,"Country Code = "+MainActivity.countries.get(position).getNationalCode(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(mainActivity, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
});
and if you click country code in listview item then it will detected;
You have not set countries list to your Listview adaptor.
When you are setting the adaptor, pass the countries list to listview adaptor.
It work successfully:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nationalcode = (String) ((TextView) view.findViewById(R.id.nationalCode)).getText();
Toast.makeText(mainActivity, "NATIONAL CODE " + nationalcode, Toast.LENGTH_SHORT).show();
}
});
Try This
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Person person = countries.get(position);
openAddPersonActivity(person.getNationalCode());
}

How to display selected installed applications in grid view

**I have this code to show the installed applications in Android. I also want to display the selected applications by the user in Grid view. How can I do that in this code?
And is there always a need for adapter for grid-view also?**
This is my first activity:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Startup extends Activity {
Button bIns, bSel;
ArrayList<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bIns = (Button) findViewById(R.id.bList);
bSel = (Button) findViewById(R.id.bGrid);
}
public void viewList(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void viewGrid(View view) {
myList = (ArrayList<String>) getIntent().getSerializableExtra("mySelectedList");
Intent intent = new Intent(getApplicationContext(), Last.class);
intent.putExtra("mySelectedList",myList);
startActivity(intent);
}
}
This is my second activity:
package com.abhi.test;
import java.util.ArrayList;
import com.abhi.test.ApplicationAdapter;
import java.util.List;
import com.example.applist.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
Button button;
Bundle bundle;
CheckBox checkbox;
ArrayList<ApplicationInfo> selectedapplication = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
button = (Button) findViewById(R.id.button);
checkbox = (CheckBox) findViewById(R.id.cb_app);
new LoadApplications().execute();
//Intent intent = new Intent(this,Last.class);
}
public void selectedApps(View view) {
//new ApplicationAdapter().selApps();
selectedapplication = ApplicationAdapter.finalList;
Intent intent = new Intent(MainActivity.this, Startup.class);
intent.putExtra("mySelectedList",selectedapplication);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (packageManager.getLaunchIntentForPackage(info.packageName) != null)
{
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.row, applist);
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
}
}
Array adapter for second activity:
package com.abhi.test;
import java.util.ArrayList;
import java.util.List;
import com.example.applist.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
int position1;
CheckBox checkBox;
private PackageManager packageManager;
public ArrayList<Boolean> checkList = new ArrayList<Boolean>();
private OnCheckedChangeListener listener;
public static ArrayList<ApplicationInfo> finalList = null;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++)
{
checkList.add(false);
}
}
#Override
public int getCount() {
if (appsList != null) {
return appsList.size();
} else {
return 0;
}
}
#Override
public ApplicationInfo getItem(int position) {
if (appsList != null) {
return appsList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override //ibuilt function getView()--responsinle for making views
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Understand
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (data != null) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
position1=position;
checkBox = (CheckBox) view.findViewById(R.id.cb_app); //understand
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position)); // set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
/* if(checkBox.isChecked())
{
finalList.add(data);
Toast.makeText(getContext(), "App Added", Toast.LENGTH_LONG).show();
}*/
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
}
};
}
This is the last activity in which I want to show the selected applications by the user:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class Last extends Activity{
GridView gridview;
ArrayList<ApplicationInfo> appList;
String[] appName = new String[100];
String[] appPack = new String[100];
String[] appComp = new String[100];
ArrayList<String> appInfo = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.last);
gridview = (GridView) findViewById(R.id.gridview);
appList = (ArrayList<ApplicationInfo>) getIntent().getSerializableExtra("mylist");
for(int i=0;i<appList.size();i++)
{
appName[i] = appList.get(i).name;
appPack[i] = appList.get(i).packageName;
appComp[i] = appName[i]+appPack[i];
appInfo.add(appComp[i]);
}
/* ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
android.R.layout.simple_list_item_1, appInfo);
gridview.setAdapter(adapter);*/
}
}
XML for the first activity:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<Button
android:id="#+id/bList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewList"
android:text="#string/bInstalledApps" />
<Button
android:id="#+id/bGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewGrid"
android:text="#string/bSelectedApps" />
</LinearLayout>
XML for the second activity:
<?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" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="selectedApps"
android:text="Done"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/button" />
</RelativeLayout>
row.xml for adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/appdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:scaleX="1.50"
android:scaleY="1.50" />
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
XML for the last activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>
A GridView is a collection of views in a grid. The Android system doesn't magically know what views you want to be in it. This is where the adapter comes in. By setting an adapter for a GridView, you tell the GridView several things about how you want it to display views including how many views there are and what each view looks like. So yes, all GridViews need adapters.

How to make a spinner work with a text field in Eclipse?

I'm currently working on making a simple conversion program and im trying to have the user select from a list of items "binary, decimal..." from one spinner menu and then select a second choice "binary, decimal.." and then use the text field to the right of the spinners to input the value and then hit a "convert" button and it spit out the conversion.
So far, ive been able to build the 2 text fields and the conversion button and have THAT work but, i can't seem to figure out how to make the text fields work with the selection on the spinner menu.
Any suggestions? This is what i currently have---______------______----- THANKS IN ADVANCE :)
MainActivity
package com.overworldinnovations.datatool;
import java.util.ArrayList;
import java.util.List;
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.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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
//import android.os.Build;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Spinner spinner1, spinner2;
private Button buttonConvert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).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.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);
}
/**
* 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_main, container,
false);
return rootView;
}
}
}
activity_main
<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"
tools:context="com.overworldinnovations.datatool.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:text="Convert" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="108dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/spinner1"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="50dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/spinner2"
android:layout_alignLeft="#+id/textView1"
android:layout_marginBottom="16dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
strings
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Data Tool</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="convert">Convert</string>
<string name="data_tool_is_an_application_that_converts_binary_to_decimal_d">Data Tool is an application that converts Binary to Decimal :D</string>
<string name ="country_prompt">Choose a country</string>
<string-array name = "type_arrays">
<item >Decimal</item>
<item >Binary</item>
<item >Hexidecimal</item>
</string-array>
</resources>
CustomOnItemSelectedListener
package com.overworldinnovations.datatool;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Categories