I have an activity that returns a list of information derived from Parse.com in a listview. I would want that each item on the list is shown individually on a page, and where user are able to swipe left or right or navigate through arrows left and right through the list to view other list item.
Below is the code for that produces the list:
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
The XML layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/logout"
android:id="#+id/logoutButton"
android:gravity="center_vertical|center_horizontal"
android:layout_gravity="center_horizontal"
android:background="#color/dark_gray"
android:textSize="24sp"
android:padding="15dp"
android:textColor="#color/sinch_purple" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textColor="#ffffff"
android:background="#drawable/bac_blue"
android:id="#+id/usersListView">
</ListView>
</RelativeLayout>
I have also have looked into http://developer.android.com/training/implementing-navigation/lateral.html, but not sure how I would incorporate that into my listview.
If you require additional information, let me know.
Try using a Viewpager, Here you have examples and documentation.
Related
I have created a todo app in android studio. when you click on the list of task item, it deletes itself. but i want to show a confirm dialog before that.i am using two java classes. MainActivity and Filehelper for this todo app.
so i used this code to delete the item and it was working:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
}
And now i am using this code with confirm dialog :
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm dialog demo !");
builder.setMessage("You are about to delete all records of database. Do you really want to proceed ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
items.remove(position);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You've changed your mind to delete tasks", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
but when i run it on my android . i see the dialog. but when i press yes it crash itself. so can you give me the right code. and also tell me the problem of my code?.
MainActivity Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private EditText ItemET;
private Button btn;
private ListView itemList;
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemET = findViewById(R.id.item_edit_text);
btn = findViewById(R.id.add_btn);
itemList = findViewById(R.id.item_list);
items = FileHelper.readData(this);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
itemList.setAdapter(adapter);
btn.setOnClickListener(this);
itemList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
if (ItemEntered.trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Please Enter some detail", Toast.LENGTH_LONG).show();
} else {
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}
break;
}
}
// Confirm box
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm dialog demo !");
builder.setMessage("You are about to delete all records of database. Do you really want to proceed ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
items.remove(position);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You've changed your mind to delete all records", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
FileHelper Code :
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> items, Context context){
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
itemList = (ArrayList<String>) ois.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return itemList;
}
}
here is also my MainActivity.xml
<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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="12dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/item_edit_text"
android:hint="Enter Item"
android:layout_width="0dp"
android:layout_weight="1.9"
android:layout_marginRight="20dp"
android:layout_height="wrap_content" />
<Button
android:background="#drawable/layout_bg"
android:id="#+id/add_btn"
android:text="add"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"/>
</LinearLayout>
<ListView
android:background="#drawable/layout_bg"
android:id="#+id/item_list"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textAlignment="center"
android:layout_marginBottom="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
You can create a method and call it whenever you need it
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Discard Data!");// Dialog header
builder.setMessage("Are you sure you want to discard this data?"); //disclaimer text
// yes button
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
edit_text.getText().clear(); //clear EditText
}
});
//No button
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
Send the logcat picture please. Then it will be easier to identify the problem. Also check
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
Toast.makeText(getApplicationContext(), "Check if toast is working or crush. ", Toast.LENGTH_SHORT).show();
}
});
Check toast working when "Yes" button pressed or crushed. Then you will be more sure about the problem.
I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:
Item A
Item B
Item C
Item D
Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.
Here's my codes...
Java Class:
public class MainActivity extends AppCompatActivity {
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
lstVw.setAdapter(adapter);
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String getItem = adapter.getItem(position);
getPosition = Integer.parseInt(getItem);
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText(getString(R.string.default_item_name_value));
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
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/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="650dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="650dp">
<ListView
android:id="#+id/lstView"
android:layout_width="match_parent"
android:layout_height="650dp"
tools:ignore="NestedScrolling" />
</RelativeLayout>
</ScrollView>
<include layout="#layout/action_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
Action Buttons XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">
<Button
android:id="#+id/add_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="#string/add_item_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/remove_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/add_item_btn"
android:textAllCaps="false"
android:text="Remove Item"
android:textColor="#android:color/black"
android:textSize="14sp"
android:textStyle="bold"/>
<Button
android:id="#+id/clear_list_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/remove_item_btn"
android:textAllCaps="false"
android:text="#string/clear_list_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
My Custom List Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"/>
</ScrollView>
I appreciate the help! Thanks!
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
From where are you getting this getPosition?
It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getPosition = position;
}
});
Edit:
You could go with something like this:
Create an interface that your activity will implement and will be used by your adapter to notify a position change:
public interface PositionChangeListener {
void onPositionChanged(int newPosition);
}
Create a custom adapter:
public class CustomAdapterView extends BaseAdapter {
private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;
public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
this.context = context;
this.items = items;
this.listener = listener;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
viewHolder = new ViewHolder();
viewHolder.txt = convertView.findViewById(R.id.item_tv);
viewHolder.txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onPositionChanged(position);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt.setText(items.get(position));
return convertView;
}
private class ViewHolder {
TextView txt;
}
}
And now in your activity:
public class MainActivity extends AppCompatActivity implements PositionChangeListener{
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;
#Override
public void onPositionChanged(int newPosition) {
getPosition = newPosition;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new CustomAdapterView(this, arrayList, this);
lstVw.setAdapter(adapter);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText("default item name");
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
I want to connect to paired Bluetooth devices by clicking on them using two ListViews.
One ListView should display all paired devices, those items should be clickable and get connected due to a click on the item itsself. Then this item should be displayed in the second ListView that shows connected devices.
I had several attempts to this problem but i couldnt manage to get it working. Hope you can help.
Here is my Fragment:
EDIT:
public class MainActivityFragment extends Fragment implements OnClickListener {
Button connectButton;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int ENABLE_BLUETOOTH = 1;
private static final String TAG = MainActivityFragment.class.getSimpleName();
ArrayList<String> mPairedDevicesArrayList;
ArrayAdapter<String> mPairedDevicesAdapter;
ListView listViewPaired, listViewConnected;
public void initBluetooth(){
if(!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BLUETOOTH);
}
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
mPairedDevicesArrayList = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_connect, parent, false);
connectButton = (Button) rootView.findViewById(R.id.connectButton);
connectButton.setOnClickListener(this);
listViewPaired = (ListView) rootView.findViewById(R.id.listViewPaired);
listViewConnected = (ListView) rootView.findViewById(R.id.listViewConnected);
return rootView;
}
#Override
public void onClick(View rootView){
connectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
if(mBluetoothAdapter.isDiscovering()){
Log.i(TAG, "cancel discovery");
mBluetoothAdapter.cancelDiscovery();
}
Log.i(TAG, "Bluetooth start search");
mBluetoothAdapter.startDiscovery();
getPairedDevices();
}
else {
Log.i(TAG, "Bluetooth not activated");
initBluetooth();
}
}
}); listViewPaired.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
listViewConnected.setAdapter(mPairedDevicesAdapter);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(getActivity().getApplicationContext(), "Bluetooth enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity().getApplicationContext(), "User canceled", Toast.LENGTH_LONG).show();
}
}
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = mBluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
mPairedDevicesArrayList.add(device.getName()+"\n"+device.getAddress()); mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), R.layout.fragment_connect); listViewPaired.setAdapter(mPairedDevicesAdapter);
Log.i(TAG, "devices in List");
}
}
}
Here is my Fragment-XML:
<TextView
android:text="Welcome in Fragment!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<Button
android:text="Connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:id="#+id/connectButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:background="#android:color/holo_blue_bright"
android:layout_toLeftOf="#+id/connectButton"
android:layout_toStartOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewPaired" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="#android:color/darker_gray"
android:layout_toRightOf="#+id/connectButton"
android:layout_toEndOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewConnected" />
ArrayAdapter uses a TextView to display each item within it.
See ArrayAdapter
It has a number of constructors that can be used,You can use this constructor to initialize the adapter with you data
ArrayAdapter(Context context, int resource, T[] objects).
And then set it to your listView
like this:
mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, mPairedDevicesArrayList);
listViewPaired.setAdapter(mPairedDevicesAdapter);
and to set an onClickListener for ListView rows, do that:
listViewPaired.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do you code
}
}
See more details here
I have added navigation view and drawer layout in my app. When I open and close the drawer it lags in time. opens and close slowly. I got this issue prominently on version 4.4 also on 6.0 but not as prominently as 4.4.
When I am running on 4.4 device as I open the drawer I noticed messages in log that too much work may be doing on main thread.
So I tried to comment all the code except the navigation drawer and options menu code. So after that I found it was working bit well.
Is it the issue? or some memory issue can be there? But on larger memory devices also I found the problem.
Do I need to create another activity for other code? So that drawer will work faster?
I also tried to create a fragment and replaced it in framelayout of main activity to separate the code. But it was still lagging.
If I create new activity still I need all the navigation code in that activity, it will be again a same thing.
I am not getting what can be the issue. Can anyone please help.. Thank you..
Here is code:
public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack,UpdateUserAsyncTask.UpdateUserCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactDb = new ContactTableHelper(MainActivity.this);
mDb = new UserTableHelper(MainActivity.this);
boolean result = Utility.checkAndRequestPermissions(MainActivity.this);
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(REGISTRATION_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(PUSH_NOTIFICATION));
NotificationUtils.clearNotifications(getApplicationContext());
sharedpreferences = getSharedPreferences("UserProfile", Context.MODE_PRIVATE);
mUserId = sharedpreferences.getString("userId", "");
firstTimeLogin = sharedpreferences.getBoolean("login", false);
refreshedToken = sharedpreferences.getString("deviceId", "");
parentLayout = (LinearLayout) findViewById(R.id.toolbar_container);
setupView();
mUser = new User();
url = sharedpreferences.getString("url", "");
contactList = new ArrayList<Contact>();
txtuserName = (TextView) findViewById(R.id.txtusername);
txtmobile = (TextView) findViewById(R.id.txtmobile);
profileImageView = (CircleImageView) findViewById(R.id.thumbnail);
if (profileImageView != null) {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent Intent = new Intent(MainActivity.this, ProfileActivity.class);
Intent.putExtra("user", mUser);
Intent.putExtra("url", url);
startActivity(Intent);
}
});
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(), bmOptions);
if (bitmap != null) {
profileImageView.setImageBitmap(bitmap);
} else {
profileImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_white_48dp));
}
ImageView sync = (ImageView) findViewById(R.id.sync);
sync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contactList.clear();
contactDb.deleteAllContacts();
GetContactsAsyncTask getContactsAsyncTask = new GetContactsAsyncTask(MainActivity.this, MainActivity.this, mUserId, MainActivity.this);
getContactsAsyncTask.execute(mUserId);
}
});
}
void setupView() {
File sd = Environment.getExternalStorageDirectory();
image = new File(sd + "/Profile", "Profile_Image.png");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
menuItem.setChecked(true);
FragmentManager fragmentManager = getSupportFragmentManager();
switch (menuItem.getItemId()) {
case R.id.nav_menu_contacts:
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
break;
case R.id.nav_menu_settings:
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_log_out:
SharedPreferences pref = getSharedPreferences("UserProfile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("UserUsername");
editor.remove("userId");
editor.remove("url");
editor.remove("login");
editor.remove("company");
editor.remove("emailId");
editor.remove("profileImage");
editor.remove("fullName");
editor.remove("homeAddress");
editor.remove("workAddress");
editor.remove("workPhone");
editor.remove("pass");
editor.remove("jobTitle");
editor.remove("mobileNo");
editor.commit();
mDb.deleteAllUsers();
contactDb.deleteAllContacts();
UpdateTokenAsyncTask updateTokenAsyncTask = new UpdateTokenAsyncTask(MainActivity.this, mUserId, "");
updateTokenAsyncTask.execute(mUserId, "");
finish();
i = new Intent(MainActivity.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_invite:
i = new Intent(MainActivity.this, InviteContactsActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
}
return true;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
TextView mTitle = (TextView) findViewById(R.id.toolbar_title);
final ImageView menu = (ImageView) findViewById(R.id.menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(MainActivity.this, menu);
popup.getMenuInflater().inflate(R.menu.main_pop_up_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.pendingInvites) {
startActivity(new Intent(MainActivity.this, PendingInvitesActivity.class));
} else if (item.getItemId() == R.id.feedback) {
final MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this)
.title("Feedback")
.customView(R.layout.feedback_dialog, true).build();
positiveAction = dialog.getActionButton(DialogAction.POSITIVE);
edtName = (EditText) dialog.getCustomView().findViewById(R.id.editName);
edtEmailId = (EditText) dialog.getCustomView().findViewById(R.id.editTextEmailId);
edtComment = (EditText) dialog.getCustomView().findViewById(R.id.editTextComment);
buttonSave = (Button) dialog.getCustomView().findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View view1 = getCurrentFocus();
if (view1 != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
mName = String.valueOf(edtName.getText().toString());
mEmailId = String.valueOf(edtEmailId.getText().toString());
mComment = String.valueOf(edtComment.getText().toString());
if (mComment.equals("")) {
showAlert("Please enter comments.");
} else if (mEmailId.equals("")) {
showAlert("Please enter an email-id.");
} else {
if (!isValidEmail(mEmailId)) {
showAlert("Please enter valid email id.");
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", mName);
params.put("email_id", mEmailId);
params.put("comment", mComment);
CreateFeedbackAsyncTask createFeedbackAsyncTask = new CreateFeedbackAsyncTask(MainActivity.this, MainActivity.this);
createFeedbackAsyncTask.execute(params);
dialog.dismiss();
}
}
}
});
edtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
edtComment.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
edtEmailId.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
dialog.show();
positiveAction.setEnabled(false);
return true;
}
return true;
}
});
popup.show();//showing popup menu
}
});
if (toolbar != null) {
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
#Override
public void doPostExecute(JSONArray response) throws JSONException {
contactListArray = response;
contactDb = new ContactTableHelper(MainActivity.this);
if (null == contactList) {
contactList = new ArrayList<Contact>();
}
for (int i = 0; i < contactListArray.length(); i++) {
JSONObject subObject1 = contactListArray.getJSONObject(i);
Contact contact = new Contact();
JSONObject subObject = subObject1;
String contactName = subObject.getString("user_name");
//name of the attribute in response
String pass = subObject.getString("password");
String contactId = subObject.getString("user_id");
String contactMobile = subObject.getString("mobile_no");
String contactEmailId = subObject.getString("email_id");
String contactProfile = subObject.getString("profile_image");
String fullName = subObject.getString("full_name");
String jobTitle = subObject.getString("job_title");
String homeAddress = subObject.getString("home_address");
String workPhone = subObject.getString("work_phone");
String workAddress = subObject.getString("work_address");
String company = subObject.getString("company");
contact.setmThumbnail(contactProfile);
contact.setmUserName(contactName);
contact.setmMobileNo(contactMobile);
contact.setmEmailId(contactEmailId);
contact.setmProfileImage(contactProfile);
contact.setContactId(contactId);
contact.setmHomeAddress(homeAddress);
contact.setmFullName(fullName);
contact.setmJobTitle(jobTitle);
contact.setmWorkAddress(workAddress);
contact.setmWorkPhone(workPhone);
contact.setmPass(pass);
contact.setmCompany(company);
contactList.add(contact);//adding string to arraylist
contactDb.addContact(new Contact(contactId, contactName, pass, contactMobile, contactEmailId, contactProfile, fullName, jobTitle, workAddress, workPhone, homeAddress, company));
}
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
#Override
public void onResume() {
super.onResume();
contactList.clear();
if (!firstTimeLogin) {
contactList.clear();
contactList = contactDb.getAllContacts();
mUser = mDb.getUser(mUserId);
txtuserName.setText(mUser.getmUserName());
txtmobile.setText(mUser.getmMobileNo());
} else {
new GetUserAsyncTask1(MainActivity.this,mUserId).execute(mUserId);
new GetContactsAsyncTask(this, MainActivity.this, mUserId, MainActivity.this).execute();
firstTimeLogin = false;
SharedPreferences.Editor editor = getSharedPreferences("UserProfile", MODE_PRIVATE).edit();
editor.putBoolean("login", firstTimeLogin);
editor.commit();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
final Contact contact = contactList.get(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
} else {
showAlert("Some Permissions are Denied.");
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void doPostExecute(JSONObject response, Boolean update) throws JSONException {
}
}
Main layout :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
</FrameLayout>
<!-- Your normal content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id = "#+id/toolbar_container">
<!-- We use a Toolbar so that our drawer can be displayed
in front of the action bar -->
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Contacts"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAlignment="center"
android:gravity="center_vertical|center|center_horizontal"
android:layout_toLeftOf="#+id/sync"
android:layout_toStartOf="#+id/sync"
android:layout_centerInParent="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:background="#drawable/ic_refresh_white_24dp"
android:id="#+id/sync"
android:layout_gravity = "right"
android:layout_toStartOf="#+id/menu"
android:layout_toLeftOf="#+id/menu"
android:layout_centerVertical="true"
android:layout_alignParentRight="false"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity= "end"
android:layout_marginRight="10dp"
android:background="#drawable/ic_more_vert_white_36dp"
android:id="#+id/menu"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<view
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
class="android.support.v7.widget.RecyclerView"
android:id="#+id/recycler_view"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true" />
<!-- The rest of your content view -->
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimary"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#color/yourColor"
app:itemIconTint="#color/yourColor"
app:menu="#menu/nav_menu" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/drawer_header"
android:layout_width="match_parent"
android:layout_height="103dp" />
<ExpandableListView
android:id="#+id/elvGuideNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:groupIndicator="#null"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
Do the Json Parsing and adding the Entries into the DB also in Background Thread and Pass only the ArrayList of Entries to the Main Thread, this way you can reduce the Load on the Main Thread.
Another thing you can try is Enabling hardwareAcceleration to true
Definitely try to move any database operations on another threads. Decoding that bitmap in onCreate() also is dangerous.
Maybe organising your code will help a bit.
I have a ListView in one my activity_main.xml file, the problem is, when I click on a Item in that ListView (activity_main.xml), it calls setContentView() and loads another XML file called activity_settings.xml.
The problem is, when I click the back button in activity_settings.xml (Button to call setContentView() again and go back to activity_main.xml) The ListView from activity_main.xml disappears.
I have tried about dozen ways of fixing it, but nothing seems to work.
Here is my MainActivity.java (It is pretty big):
package com.NautGames.xectav2.app;
import {...}
public class MainActivity extends ASR {
private ToggleButton homeOnOff;
HomeHoldDown hhd = new HomeHoldDown();
int keyCode;
KeyEvent event;
Context context;
private static final String LOGTAG = "Xecta";
private static final String BOTID = "e38006d97e34053e";
private TTS myTts;
private ImageButton speakButton;
private Bot bot;
Button backB1;
Button backB2;
Button backB3;
boolean mBound = false;
SimpleAdapter simpleAdpt;
BoundService myService = new BoundService();
boolean isBound = false;
EditText name, email, mMessage, subject;
String key;
String Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
//Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
if(id == 0)
{
setContentView(R.layout.activity_settings);
}
if(id == 1)
{
setContentView(R.layout.activity_about);
}
if(id == 2)
{
setContentView(R.layout.activity_feedback);
}
}
});
}
public void onClickSend(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"name#email.com"});
i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
i.putExtra(Intent.EXTRA_TEXT , mMessage.getText().toString());
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//from here
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
BoundService.MyLocalBinder binder = (BoundService.MyLocalBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
//to HERE
public void showTime(View view)
{
myService.getCurrentTime();
}
/************************************************************************
* WHEN THE USER TURNS THE HOME LISTENING ON AND OFF
* IT WILL START SERVICE AND STOP SERVICE
*************************************************************************/
/*public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home ON", Toast.LENGTH_LONG).show();
//startService(new Intent(getBaseContext(), Service1.class));
} else {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home OFF", Toast.LENGTH_LONG).show();
//stopService(new Intent(getBaseContext(), LocalService.class));
}
}*/
#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;
}
/*public void onClickService(View view)
{
if(isApplicationSentToBackground(context))
{
hhd.onKeyLongPress(keyCode, event);
}
}*/
/**************************************************************************
* WHEN THE USER HOLDS DOWN THE HOME BUTTON
*************************************************************************/
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(MainActivity.this, "Key pressed long!", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyLongPress(keyCode, event);
}
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
}
// The data to show
List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
planetsList.add(newList("page", "Settings"));
planetsList.add(newList("page", "About"));
planetsList.add(newList("page", "FeedBack"));
}
private HashMap<String, String> newList(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
public void onClick(View view)
{
speakButton = (ImageButton) findViewById(R.id.speech_btn);
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
private void setSpeakButton() {
speakButton = (ImageButton) findViewById(R.id.speech_btn);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
});
}
/**
* Provides feedback to the user when the ASR encounters an error
*/
public void processAsrError(int errorCode) {
String errorMessage;
switch (errorCode)
{
case SpeechRecognizer.ERROR_AUDIO:
errorMessage = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
errorMessage = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
errorMessage = "Insufficient permissions" ;
break;
case SpeechRecognizer.ERROR_NETWORK:
errorMessage = "Network related error" ;
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
errorMessage = "Network operation timeout";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
errorMessage = "RecognitionServiceBusy" ;
break;
case SpeechRecognizer.ERROR_SERVER:
errorMessage = "Server sends error status";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
errorMessage = "No matching message" ;
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
errorMessage = "Input not audible";
break;
default:
errorMessage = "ASR error";
break;
}
try {
myTts.speak(errorMessage,"EN");
} catch (Exception e) {
Log.e(LOGTAG, "English not available for TTS, default language used instead");
}
//If there is an error, shows feedback to the user and writes it in the log
Log.e(LOGTAG, "Error: "+ errorMessage);
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
public void processAsrReadyForSpeech() {
Toast.makeText(this, "I'm listening", Toast.LENGTH_LONG).show();
}
public void processAsrResults(ArrayList<String> nBestList, float[] confidences) {
String bestResult = nBestList.get(0);
Log.d(LOGTAG, "Speech input: " + bestResult);
// insert %20 for spaces in query
bestResult = bestResult.replaceAll(" ", "%20");
bot.initiateQuery(bestResult);
//Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
myTts.shutdown();
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
setContentView(R.layout.activity_main);
newList(key, Name);
initList();
}
#Override
public void onStop()
{
super.onStop();
Toast.makeText(MainActivity.this, "Bye bye!", Toast.LENGTH_SHORT).show();
onKeyLongPress(keyCode, event);
}
#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);
}
}
onClickBack is the button to go back to activity_main.xml, I am also initialising the ListView in onCreate().
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/onericblur"
android:orientation="vertical"
android:paddingBottom="5dp"
android:onClick="onClick"
android:weightSum="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#000000"
android:paddingBottom="10dip"
android:paddingTop="10dip"
android:text="#string/title"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
<ViewAnimator
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewAnimator"
android:layout_gravity="right" />
<ImageButton
android:id="#+id/speech_btn"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/xectaicon"
android:onClick="onClick"
android:layout_marginTop="32dp"
android:layout_gravity="center_horizontal|top" />
<ListView
android:layout_width="match_parent"
android:layout_height="127dp"
android:id="#+id/listView"
android:layout_weight="1.22"
android:background="#android:drawable/screen_background_light_transparent" />
</LinearLayout>
And activity_settings...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="#drawable/onericblur">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/listSeparatorTextViewStyle"
android:text="Settings"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textColor="#android:color/black" />
<TextView
android:layout_width="291dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Xecta is currently in Beta being tested, you can request settings by going to the feedback section. Sorry!"
android:id="#+id/textView2"
android:layout_weight="0.04"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:gravity="center|top" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back to home"
android:id="#+id/button3"
android:onClick="onClickBack"
android:layout_gravity="center_horizontal" />
</LinearLayout>
What could be causing the problem?!?!?
Thanks.
As suggested by Ram Kiran, it's better to have different activities for Settings / Home.
The problem with the code you have posted is that you are not populating the list with the contents when you press back. I believe it should be fixed with the following code,
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(simpleAdpt);
}
Basically when you call setContentView(layoutId) new view will be inflated from the layout and you need to do all the UI lookup, initialization again.
I dont think loading xml files repeatedly in same activity is a good one. Try to use two activities instead of loading different xml files in same activity.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findviewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
Intent n = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(n);
}
}
SettingsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Buttoon btn = (Button) findviewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent n = new Intent(getApplicationContext(),MainActivity.class);
startActivity(n);
}
});
Try out as below:
#Override
public void onResume()
{
super.onResume();
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
}