Android ArrayAdapter NullPointerException getID - java

I'm having a bit of a problem with my code for a ListView, it is supposed to present a list of available devices that have not yet been paired with the device.
I've included the error below:
FATAL EXCEPTION: main
at com.zephyr.bolt.UnpairedDeviceViewer$StableArrayAdapter.getItemId(UnpairedDeviceViewer.java:110)
at android.widget.AbsListView.obtainView(AbsListView.java:2198)
(I didn't include the entire error sadly, the error is on my tablet, and I can't seem to copy it out of AIDE)
Below is the referenced class file and it's XML file
UnpairedDeviceViewer.java
package com.zephyr.bolt;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class UnpairedDeviceViewer extends Activity{
Activity a = this;
private ListView listview;
private Button b1;
public StableArrayAdapter adapter;
private ArrayList strings;
private BroadcastReceiver recv;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.udv);
b1 = (Button) findViewById(R.id.b5);
listview = (ListView) findViewById(R.id.l2);
strings = new ArrayList<String>();
adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, strings);
recv = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
adapter.add(device.getName() + "\n" + device.getAddress());
adapter.notifyDataSetChanged();
}
else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
{
Toast.makeText(a, "Device Discovery Started", Toast.LENGTH_LONG).show();
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Toast.makeText(a, "Device Discovery Completed", Toast.LENGTH_LONG).show();
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(recv, filter);
listview.setAdapter(adapter);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.bTAdapter.startDiscovery();
}
});
}
protected void onDestroy()
{
MainActivity.bTAdapter.cancelDiscovery();
unregisterReceiver(recv);
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
udv.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:id = "#+id/b5"
android:layout_centerHorizontal="true"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "Begin Discovery"
/>
<ListView
android:id = "#+id/l2"
android:layout_below="#+id/b5"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>

Your mIdMap is an overly complicated way of doing what ArrayAdapter already does. Its implementation of getItemId(pos) returns pos.
Note you are only building your mIdMap once, any items you add post-construct - like in your receiver callback - will not have ids, and will cause a NPE in your getItemId implementation trying to unbox null.
Also, calling notifyDataSetChanged() is unnecessary, ArrayAdapter will automatically call it after each add() by default.

Related

how to show available wifi networks on a button click in android?

I'm working to build a simple android 8.0+ application which shows the Wi-Fi scan result in a list within that app.
I've tried all the given solutions in stack overflow, but I didn't get result'for listing the available networks on the screen. Following is the code I've tried to get the result.
package com.example.wifi_application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity{
private WifiManager wifiManager;
private ListView listView;
private Button buttonScan;
private int size = 0;
private List<ScanResult> results;
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonScan = findViewById(R.id.scanBtn);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanWifi();
}
});
listView = findViewById(R.id.wifiList);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// assert wifiManager != null;
if (!wifiManager.isWifiEnabled()) {
Toast.makeText(this, "WiFi is disabled ... We need to enable it", Toast.LENGTH_LONG).show();
wifiManager.setWifiEnabled(true);
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
scanWifi();
}
private void scanWifi() {
arrayList.clear();
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
Log.d("WifScanner", "scanWifi");
Toast.makeText(this, "Scanning WiFi ...", Toast.LENGTH_SHORT).show();
}
BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("WifScanner", "onReceive");
results = wifiManager.getScanResults();
size = results.size();
unregisterReceiver(this);
try {
while (size >= 0) {
size--;
arrayList.add(results.get(size).SSID);
adapter.notifyDataSetChanged();
}
}
catch (Exception e) {
Log.w("WifScanner", "Exception: " + e);
}
}
};
}
this is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/wifiList"
android:layout_width="match_parent"
android:layout_height="312dp"
android:layout_weight="0.97"/>
<Button
android:id="#+id/scanBtn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:layout_margin="15dp"
android:background="#android:color/holo_red_light"
android:text="Scan WiFi"/>
</LinearLayout>

StackoverflowError while inflating Fragment

I have some weird Stackoverflowerror which is thrown in the onCreateView() method of a Fragment i use.
As you can see in this image, that is the method where it breaks. The First TODO should be where the error comes from.
I have no idea what could be wrong with that line:
view = inflater.inflate(R.layout.activity_chat, container, false); //it breaks here
I would be very glad to hear any tipps from anyone.
Edit: this is another strange errorreport i got after the initial error:
Edit: Content of Activity_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright"
android:orientation="vertical">
<fragment
android:id="#+id/msg_list"
android:name="com.example.f00.mobileapp.listener.TabFragment2"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
tools:layout="#layout/tab_fragment_2" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_green_dark">
<Button
android:id="#+id/send_btn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Send" />
<EditText
android:id="#+id/msg_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/send_btn"
android:layout_toLeftOf="#+id/send_btn"/>
</RelativeLayout>
</LinearLayout>
Edit: TabFragment2.java:
package com.example.f00.mobileapp.listener;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.f00.mobileapp.R;
import com.example.f00.mobileapp.activities.MainActivity;
import com.example.f00.mobileapp.application.Common;
import com.example.f00.mobileapp.fragments.EditContactDialog;
import com.example.f00.mobileapp.fragments.MessagesFragment;
import com.example.f00.mobileapp.utils.AsyncResponse;
import com.example.f00.mobileapp.utils.DataProvider;
import com.example.f00.mobileapp.utils.GcmUtil;
import com.example.f00.mobileapp.utils.Utils;
import java.io.IOException;
import java.util.Random;
// Chat chat real chat.
public class TabFragment2 extends Fragment implements MessagesFragment.OnFragmentInteractionListener,
EditContactDialog.OnFragmentInteractionListener, View.OnClickListener {
View view;
private EditText msgEdit;
private Button sendBtn;
private String profileId;
private String profileName;
private String profileEmail;
private GcmUtil gcmUtil;
public Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.tab_fragment_2, container, false); //TODO this it where it breaks
//////////////
profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
sendBtn.setOnClickListener(this);
android.app.ActionBar actionBar = getActivity().getActionBar(); //TODO
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Cursor c = getActivity().getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
if (c.moveToFirst()) {
profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
actionBar.setTitle(profileName);
}
actionBar.setSubtitle("connecting ...");
getActivity().registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
gcmUtil = new GcmUtil(getActivity().getApplicationContext());
///////////
return view;
}
/*
/**
* The important piece of code is in onCreate() where we instantiate GcmUtil.
* This triggers registration with GCM if it's not already done.
* Recall that GcmUtil broadcasts the registration status which this activity
* registers to listen.
*
* #param savedInstanceState
*/
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.activity_chat);
getActivity().getIntent().getStringArrayExtra(Common.PROFILE_ID);
profileId = getActivity().getIntent().getStringExtra(Common.PROFILE_ID);
msgEdit = (EditText) getActivity().findViewById(R.id.msg_edit);
sendBtn = (Button) getActivity().findViewById(R.id.send_btn);
sendBtn.setOnClickListener(this);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Cursor c = getContentResolver().query(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), null, null, null, null);
if (c.moveToFirst()) {
profileName = c.getString(c.getColumnIndex(DataProvider.COL_NAME));
profileEmail = c.getString(c.getColumnIndex(DataProvider.COL_EMAIL));
actionBar.setTitle(profileName);
}
actionBar.setSubtitle("connecting ...");
registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
gcmUtil = new GcmUtil(getApplicationContext());
}*/
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
EditContactDialog dialog = new EditContactDialog();
Bundle args = new Bundle();
args.putString(Common.PROFILE_ID, profileId);
args.putString(DataProvider.COL_NAME, profileName);
dialog.setArguments(args);
dialog.show(getActivity().getSupportFragmentManager(), "EditContactDialog");
return true;
case android.R.id.home:
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_btn:
send(msgEdit.getText().toString());
msgEdit.setText(null);
break;
}
}
#Override
public void onEditContact(String name) {
getActivity().getActionBar().setTitle(name); //TODO
}
#Override
public String getProfileEmail() {
return profileEmail;
}
/**
* Finally to send a message we post the data to our server asynchronously.
*
* #param txt
*/
private void send(final String txt) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Utils sendMsg = new Utils(new AsyncResponse() {
#Override
public void asyncResponse(Object output, boolean status) {
}
});
//TODO
sendMsg.sendChatMessage(System.identityHashCode(new Random()), txt, getActivity().getApplicationContext());
/* ServerUtilities.send(txt, profileEmail);
ContentValues values = new ContentValues(2);
values.put(DataProvider.COL_TYPE, DataProvider.MessageType.OUTGOING.ordinal());
values.put(DataProvider.COL_MESSAGE, txt);
values.put(DataProvider.COL_RECEIVER_EMAIL, profileEmail);
values.put(DataProvider.COL_SENDER_EMAIL, Common.getPreferredEmail());
values.put(DataProvider.COL_ID, System.currentTimeMillis());
getContentResolver().insert(DataProvider.CONTENT_URI_MESSAGES, values);
*/
} catch (IOException ex) {
msg = "Message could not be sent";
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
if (!TextUtils.isEmpty(msg)) {
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
public void sendNewOrder(final String text) {
//TODO
}
#Override
public void onPause() {
ContentValues values = new ContentValues(1);
values.put(DataProvider.COL_COUNT, 0);
getActivity().getContentResolver().update(Uri.withAppendedPath(DataProvider.CONTENT_URI_PROFILE, profileId), values, null, null);
super.onPause();
}
#Override
public void onDestroy() {
getActivity().unregisterReceiver(registrationStatusReceiver);
gcmUtil.cleanup();
super.onDestroy();
}
/**
*
*/
{ }
private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
case Common.STATUS_SUCCESS:
getActivity().getActionBar().setSubtitle("online");
break;
case Common.STATUS_FAILED:
getActivity().getActionBar().setSubtitle("offline");
break;
}
}
}
};
}
I think you are doing a lot of things in your onCreateView - My recommendation is that you move the rest of the code in the onActivityCreated(Bundle savedInstanceState). Change the onCreateView into:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_chat, container, false);
return rootView;
}
Then you can move the rest of the code to onActivityCreated. This method is called after the onCreateView() method when the host activity is created.
Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method.

Cant display the item of my List View

I have a project for my school making a FAB and floating label.
The question is, the item on the list view is not diplayed and i having a hard time fixing on that.
I have two java class. MainActivity.java and MyCustomAdapter.java
Here is code for MainActivity.java
package com.example.sugara.floatingaction_mario;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.list);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Row " + position + " clicked", Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton FAB = (FloatingActionButton) findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputDialog();
}
});
final ArrayList list = new ArrayList<>();
list.add("Richard Felmon age 23");
list.add("Nestor Mersy age 44");
list.add("Bruto Char age 12");
list.add("Filemon Mandela age 33");
list.add("Sukyuu Nirasu age 39");
// final MainActivity adapter = new MyCustomAdapter(MainActivity.this, list);
// myList.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showInputDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_second, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false).setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Data saved ", Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
And here is my MyCustomAdapter.java
package com.example.sugara.floatingaction_mario;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MyCustomAdapter extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//Displaying TextInputLayout Error
TextInputLayout lNameLayout = (TextInputLayout) findViewById(R.id.lNameLayout);
lNameLayout.setErrorEnabled(true);
lNameLayout.setError("Min 2 chars required");
//Displaying EditText Error
EditText age = (EditText) findViewById(R.id.age);
age.setError("Required");
}
}
I have tried making adapter for listview but when i do so
It is clashing with
public class MyCustomAdapter extends AppCompatActivity {
Can you help me fixing this and make the input displayed on the listview too?
I am sorry if it's confusing, it's my first time posting a question like this
If you want only text in the ListView than you may not customize the Adapter Class.
Please use this. This will help you.
Create layout with TextView(layout_list.xml)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Modify MainActivity.java like this.
...
final ArrayList list = new ArrayList<>();
list.add("Richard Felmon age 23");
list.add("Nestor Mersy age 44");
list.add("Bruto Char age 12");
list.add("Filemon Mandela age 33");
list.add("Sukyuu Nirasu age 39");
myList.setAdapter(new ArrayAdapter<String>(this, R.layout.layout_list, list));
Your Adapter must extend an Adapter class of Android. Try
public class MyCustomAdapter extends BaseAdapter {
and then implementing the necessary methods.

How do I change my Activity's fragment container's background with a custom dialog with code?

Fairly new to Android and I am trying to do some background color changes. Basically I have a main activity that only has a FrameLayout in it's xml. When the activity is created it opens up a fragment for my program. I have a menu item that when clicked pops a dialog box with 3 seekbars(red, green, blue). I want to change the background color to whatever the seekbars position is. I have all the code finished for the seekbars and I know it works on a simple app I created. For reasons to me unknown my app fails when i try to open the dialog box. What is the proper way to set this up in the Main Activity? I want the user to be able to change the background color whenever they want. All my fragment layouts are transparent. This is the tutorial I have been working off of. http://android-er.blogspot.com/2009/08/change-background-color-by-seekbar.html Any advice would be great. I think my problem is I do not fully understand how to access my main_activity's FrameLayout from with-in my MainActivity java class.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#e3a153">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentView"></FrameLayout>
</LinearLayout>
Color_seekbar_selecter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change color"
/>
<SeekBar
android:id="#+id/mySeekingBar_R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_B"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
</LinearLayout>
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="#+id/menu_settings"
android:title="Green" />
<item android:id="#+id/menu_red"
android:title="Red" />
<item android:id="#+id/menu_blue"
android:title="Blue" />
<item android:id="#+id/menu_tan"
android:title="Tan" />
</menu>
MainActivity.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends ActionBarActivity {
//public CategoryFragment categoryFragment;
//public RecipeFragment recipeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
CategoryFragment categoryFragment = new CategoryFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentView, categoryFragment, "categoryFrag")
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_green:
}
return super.onOptionsItemSelected(item);
}
}
I have tried for hours to figure this out, but I just don't know where to put what.
This is the code from the example that I found in the link posted above.
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class SeekColorActivity extends Activity {
private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
updateBackground();
redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
updateBackground();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private void updateBackground()
{
seekR = redSeekBar.getProgress();
seekG = greenSeekBar.getProgress();
seekB = blueSeekBar.getProgress();
mScreen.setBackgroundColor(
0xff000000
+ seekR * 0x10000
+ seekG * 0x100
+ seekB
);
}
}
categoryFragment.java
package com.example.mikesgamerig.finalproject;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
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.ListView;
import java.util.ArrayList;
import java.util.List;
public class CategoryFragment extends Fragment {
private ArrayList<String> categoryNameArrayList;
private ArrayAdapter<String> adapter;
private AlertDialog alertDialog;
private AlertDialog alertDialogDelete;
private EditText categoryEditText;
private String getCategoryName;
private List<Category> cats;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create view
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
//initialize all variables and widgets
inflater = getLayoutInflater(savedInstanceState);
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setView(inflater.inflate(R.layout.dialog_add_category, null));
alertDialogDelete = new AlertDialog.Builder(getActivity()).create();
alertDialogDelete.setView(inflater.inflate(R.layout.dialog_delete_category, null));
Button buttonAddCategory = (Button) rootView.findViewById(R.id.addCategoryButton);
ListView categoryListView = (ListView) rootView.findViewById(R.id.list);
//Array list to store names of categories
categoryNameArrayList = new ArrayList<String>();
//List of Category Objects
cats = Category.listAll(Category.class);
getCategoryNames();
//iterate through the CategoryList and attach to the ArrayList
//create adapter and fill the listView with all the name of categories
adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.label, categoryNameArrayList);
categoryListView.setAdapter(adapter);
//set OnClick listener for the add category Button.
// This calls another method that will open a custom dialog box
buttonAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisplayAddCategoryDialogBox();
}
});
//set an onItemLongClick listener for the ListView.
//First have to setLongClickable to true.
//the OnItemLongClick listener will call a method to open a custom Dialog to delete a category.
categoryListView.setLongClickable(true);
categoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
DeleteCategory(i);
return true;
}
});
//opens up a new fragment with a list of recipes for the specific category.
categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = categoryNameArrayList.get(i);
RecipeFragment fragment = new RecipeFragment();
fragment.SetTitleName(name);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragmentView, fragment)
.addToBackStack(null).commit();
}
});
return rootView;
}
//This method will Display a custom add category Dialog Box.
public void DisplayAddCategoryDialogBox(){
//Show the Dialog box to enter a new category name.
alertDialog.show();
categoryEditText = (EditText) alertDialog.findViewById(R.id.categoryEditText);
Button saveCategoryDialogBtn = (Button) alertDialog.findViewById(R.id.saveBtn);
Button cancelDialogButton = (Button) alertDialog.findViewById(R.id.cancelBtn);
saveCategoryDialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCategoryName = categoryEditText.getText().toString();
//Log.d("STRING VALUE:", getCategoryName);
Category test = new Category(getCategoryName);
test.save();
categoryNameArrayList.add(test.getName());
//Log.d("added Value: ", test.getName());
adapter.notifyDataSetChanged();
alertDialog.hide();
}
});
cancelDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.hide();
}
});
}
//this method will display a custom Delete Category Alert Dialog box.
public void DeleteCategory(final int i)
{
alertDialogDelete.show();
Button noBtn = (Button) alertDialogDelete.findViewById(R.id.noBtn);
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialogDelete.hide();
}
});
Button yesBtn = (Button) alertDialogDelete.findViewById(R.id.yesBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tempString = categoryNameArrayList.get(i);
//Log.d("VALUE OF STRING= ", tempString);
categoryNameArrayList.remove(i);
for (Category category : cats) {
String name = category.getName();
if (name.equals(tempString)) {
category.delete();
}
}
adapter.notifyDataSetChanged();
alertDialogDelete.hide();
}
});
}
//Filles the Array
public void getCategoryNames()
{
for(Category category : cats)
{
String name = category.getName();
categoryNameArrayList.add(name);
}
}
}

The adapter does not call getView () when using ListView in Fragment

So I was faced with yet another "surprise" problem when writing your application. I know that there ListFragment, but using a Fragment. When I put the markup for a fragment of a ListView, when you call the adapter in the list does not function adds elements - not a cunning way I tracked on the logs that you do not call getView (). What is more interesting - if I do not use instead of just a list of the fragment and you add the adapter works well when everything - the list is filled. I can not understand why this is happening - why in the fragment list of works not adequate.
activity_start.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:scrollbars="vertical"
android:scrollbarStyle="insideInset"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="#e8e8e8"
>
<Button
android:id="#+id/button_add_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableRight="#drawable/green_add"
android:drawablePadding="5dp"
android:text="ADD URL"
/>
<LinearLayout
android:id="#+id/linear_layout_list_show_monitor_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border_background"
android:orientation="vertical"
android:padding="1dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
>
<!-- <ListView
android:id="#+id/list_view_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> -->
<fragment
android:id="#+id/fragment_list"
android:name="pront.android.exservice.FragmentList"
android:layout_width="match_parent"
android:layout_height="300dp"/>
</LinearLayout>
StartActivity.java
import java.util.ArrayList;
import pront.android.exservice.FragmentDialogAddNewUrl.FragmentDialogAddNewUrlConectActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout.LayoutParams;
import android.widget.Toast;
public class StartActivity
extends FragmentActivity
implements OnClickListener,
FragmentDialogAddNewUrlConectActivity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().addFlags
(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_start);
listViewUrl = (ListView) findViewById(R.id.list_view_fragment);
screenWidthPx = this.getResources().getDisplayMetrics().widthPixels;
screenHeightPx = this.getResources().getDisplayMetrics().heightPixels;
layoutMarginPx = 16;
screenDp = this.getResources().getDisplayMetrics().density;
layoutMarginDp = (int)(layoutMarginPx*screenDp);
typefaceRoboto = Typeface.createFromAsset(getAssets(),
"Roboto-Thin.ttf");
LinearLayout linearLayout = (LinearLayout)
findViewById(R.id.linear_layout_list_show_monitor_url);
LayoutParams layoutParams =
new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(layoutMarginDp, layoutMarginDp,
layoutMarginDp, layoutMarginDp);
linearLayout
.setLayoutParams(layoutParams);
buttonAddUrl = (Button) findViewById(R.id.button_add_url);
buttonAddUrl.setTypeface(typefaceRoboto, Typeface.BOLD);
buttonAddUrl.setOnClickListener(this);
broadcastReceiver = new MyBroadcastReceiver();
intentFilter = new IntentFilter(BROADCAST);
registerReceiver(broadcastReceiver, intentFilter);
}
public void onStart(){
super.onStart();
}
public void onRestart(){
super.onRestart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
public void onClick(View view) {
if(view.getId() == R.id.button_add_url){
buttonAddUrl.setClickable(false);
fragmentDialogAddNewUrl = new FragmentDialogAddNewUrl();
fragmentDialogAddNewUrl.show(this.getSupportFragmentManager(),
"fragmentDialogAddNewUrl");
buttonAddUrl.setClickable(true);
}
}
public void fragmentDialogClickButtonListener(String url,
String pathFavIcon)
{
fragmentDialogAddNewUrl.onDestroyView();
this.url = url;
Toast toastInfo = Toast
.makeText(this.getApplicationContext(),
"Service start monitor\n"+url,
Toast.LENGTH_LONG);
toastInfo.setGravity(Gravity.TOP, 0, 0);
toastInfo.show();
arrayListUrl.add(new UrlBox(this.getApplicationContext(),
url,
pathFavIcon));
Log.d("StartActivity", "fragmentDialogClick...() listViewUrl.setAdapter()");
FragmentList fragmentList = (FragmentList) this.getSupportFragmentManager().findFragmentById(R.id.fragment_list);
fragmentList.setAdapter(arrayListUrl);
// MyListAdapter adapter = new MyListAdapter(this, R.layout.expandable_list_view_child_item, arrayListUrl);
// adapter.notifyDataSetChanged();
// listViewUrl.setAdapter(adapter);
}
public static class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("", intent.getIntExtra("RESULT", 0)+"");
}
}
private Button buttonAddUrl;
private ListView listViewUrl;
private MyBroadcastReceiver broadcastReceiver;
private IntentFilter intentFilter;
private Typeface typefaceRoboto;
private DialogFragment fragmentDialogAddNewUrl;
private MyListAdapter myListAdapter = null;
private ArrayList<UrlBox> arrayListUrl = new ArrayList<UrlBox>();
private int layoutMarginPx;
private float screenDp;
private int screenWidthPx;
private int screenHeightPx;
private int layoutMarginDp;
private ArrayList<String> childUrl = new ArrayList<String>();
private ArrayList<Drawable> childFavIcon = new ArrayList<Drawable>();
private String url;
private final static String BROADCAST = "pront.android.exservice";
}
FragmentList.java
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class FragmentList extends Fragment {
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
listView = (ListView) inflater.inflate(R.layout.layout_fragment_list, null, false).findViewById(R.id.list_view_fragment);
return inflater.inflate(R.layout.layout_fragment_list, null, false);
}
public void setAdapter(ArrayList<UrlBox> arrayList){
listAdapter = new MyListAdapter(getActivity(), R.layout.expandable_list_view_child_item, arrayList);
listAdapter.notifyDataSetChanged();
if(listView != null){
listView.setAdapter(listAdapter);
System.out.println("set adapter");
}
}
MyListAdapter listAdapter;
ListView listView;
}
MyListAdapter.java
import java.util.ArrayList;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter{
MyListAdapter(Activity context, int layoutResourceId, ArrayList<UrlBox> arrayList) {
super(context, layoutResourceId);
Log.d("MyListAdapter", "constructor");
this.context = context;
this.arrayListUrlBox = arrayList;
this.layoutResourceId = layoutResourceId;
}
#Override
public View getView (int position, View convertView, ViewGroup parent){
Log.d("MyListAdapter", "getView");
View returnView = convertView;
ListItemTagHolder tag = null;
if(convertView == null){
LayoutInflater inflater = context.getLayoutInflater();
returnView = inflater.inflate(layoutResourceId, null, false);
tag = new ListItemTagHolder();
tag.ImageViewFavicon = (ImageView) returnView.findViewById(R.id.image_view_favicon);
tag.ImageViewStatus = (ImageView) returnView.findViewById(R.id.image_view_status);
tag.TextViewUrl = (TextView) returnView.findViewById(R.id.text_view_url);
returnView.setTag(tag);
}
else{
tag = (ListItemTagHolder) returnView.getTag();
}
tag.ImageViewFavicon.setImageDrawable(arrayListUrlBox.get(position).getDrawableFavIcon());
tag.ImageViewStatus.setImageDrawable(arrayListUrlBox.get(position).getDrawableFavIcon()); // !
tag.TextViewUrl.setText(arrayListUrlBox.get(position).getUrl());
return returnView;
}
#Override
public int getCount() {
return arrayListUrlBox.size();
}
public UrlBox getItem(int position) {
return arrayListUrlBox.get(position);
}
private ArrayList<UrlBox> arrayListUrlBox;
private Activity context;
private int layoutResourceId;
static class ListItemTagHolder{
protected ImageView ImageViewFavicon;
protected ImageView ImageViewStatus;
protected TextView TextViewUrl;
}
}
The issue is related to MyListAdapter. You have two options:
Override getCount() and let it returns the number of items in your dataset
Pass to the super() your dataset
For instance, in your adapter:
#Override
public int getCount() {
return arrayListUrlBox.size();
}
or inside MyListAdapter constructor you can call:
super(context, layoutResourceId, arrayList);
instead of
super(context, layoutResourceId);
Hi modify your MyListAdapter as below
public class MyListAdapter extends ArrayAdapter**<UrlBox>** {
MyListAdapter(Activity context, int layoutResourceId, ArrayList<UrlBox> arrayList) {
super(context, layoutResourceId, arrayList);
Log.d("MyListAdapter", "constructor", **arrayList**);
this.context = context;
this.arrayListUrlBox = arrayList;
this.layoutResourceId = layoutResourceId;
}
....<continue with rest part of your code>...
There is 2 places i have changed.. Hope this will do the work.

Categories