Starting an activity shows Android - NullPointerException: storage == null [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have an app in which when an activity is started shows nullpointer exception, but I can't understand what the error is and where I'm doing wrong. I'm new to android and I would be grateful if you could help. Thanks in advance.`
This is the activity which shows the error when started AccountsActivity.java
public class AccountsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://xyz.in/view_json.php?device_id=" + token;
private ListView listView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AccountsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is ParseJSON.java class
public class AccountsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://sovran.in/sov2fa_v2/view_json.php?device_id=" + token;
private ListView listView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AccountsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is CustomList.java
public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] mem_codes;
private String[] created_ons;
private Activity context;
public CustomList(Activity context, String[] ids, String[] mem_codes, String[] created_ons) {
super(context, R.layout.list_view_layout, ids);
this.context = context;
this.ids = ids;
this.mem_codes = mem_codes;
this.created_ons = created_ons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewMemCode = (TextView) listViewItem.findViewById(R.id.textViewMem_code);
TextView textViewCreatedOn = (TextView) listViewItem.findViewById(R.id.textViewCreated_on);
textViewId.setText(ids[position]);
textViewMemCode.setText(mem_codes[position]);
textViewCreatedOn.setText(created_ons[position]);
return listViewItem;
}
}
And this is the error log
07-15 14:04:46.269 32255-32255/com.sovran.sov2fa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sovran.sov2fa, PID: 32255
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:383)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:378)
at com.sovran.sov2fa.AccountsActivity.<clinit>(AccountsActivity.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method) 
at java.lang.Class.newInstance(Class.java:1606) 
at android.app.Instrumentation.newActivity(Instrumentation.java:1071) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5653) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

Do the initialization of your myPrefs attribute within onCreate()-method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
...
}

Related

creating pop up window

I'm creating a pop-up window on button click. But, I'm getting error on getSupportFragmentManager();
public class PrizeList extends AppCompatDialogFragment {
TextView players, prizePoolList, perKill, rank1, rank2, rank3;
SeekBar seekBar;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.prize_list_layout, null);
builder.setView(view).setTitle("Prize List")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
players = view.findViewById(R.id.players);
prizePoolList = view.findViewById(R.id.prizePoolList);
perKill = view.findViewById(R.id.perKill);
rank1 = view.findViewById(R.id.rank1);
rank2 = view.findViewById(R.id.rank2);
rank3 = view.findViewById(R.id.rank3);
seekBar = view.findViewById(R.id.seekBar);
return builder.create();
}
}
Adapter
holder.prizeList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
Toast.makeText(v.getContext(), "prize list clicked", Toast.LENGTH_SHORT).show();
}
});
}
private void openDialog() {
PrizeList prizeList = new PrizeList();
prizeList.show(prizeList.requireActivity().getSupportFragmentManager(), "Prize");
}
The error I'm getting,
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luteraa.luteraaesports, PID: 6355
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.fragment.app.FragmentManager androidx.fragment.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
at com.luteraa.luteraaesports.BGMICategoryAdapter.openDialog(BGMICategoryAdapter.java:93)
at com.luteraa.luteraaesports.BGMICategoryAdapter.access$000(BGMICategoryAdapter.java:25)
at com.luteraa.luteraaesports.BGMICategoryAdapter$1.onClick(BGMICategoryAdapter.java:76)
at android.view.View.performClick(View.java:7191)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7164)
at android.view.View.access$3500(View.java:821)
at android.view.View$PerformClick.run(View.java:27856)
at android.os.Handler.handleCallback(Handler.java:914)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
DataAdapter adapter = new DataAdapter(MainActivity.this,tasks,getSupportFragmentManager());
you can pass the parameter getSupportFragmentManager in
adapter
calling
and get the constructor in getSupportFragmentManager like this
DataAdapter(Context context, List<Task> tasklist,
FragmentManager
supportFragmentManager) {
this.context = context;
this.taskList = tasklist;
this.supportFragmentManager=supportFragmentManager;
}
After pass the object supportFragmentManager in the prizeList
show
method
PrizeList prizeList = new PrizeList();
prizeList.show(supportFragmentManager, "Prize List");
also work in my project so this help to solve your error in
supportFragmentManager

Bluetooth beacon Scanning using android beacon library

I have a problem every time i open an activity (blueToothSearch.java) the following error occurs in my logcat.
12-04 18:57:52.317 5354-5354/com.example.admin.paniccenter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.paniccenter, PID: 5354
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.admin.paniccenter/com.example.admin.paniccenter.blueToothSearch}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at org.altbeacon.beacon.BeaconManager.<init>(BeaconManager.java:323)
at org.altbeacon.beacon.BeaconManager.getInstanceForApplication(BeaconManager.java:315)
at com.example.admin.paniccenter.blueToothSearch.<init>(blueToothSearch.java:65)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Below is my blueToothSearch activity which i want to use to display a list of beacons in my region.
public class blueToothSearch extends AppCompatActivity implements BeaconConsumer {
private static final String TAG = "blueToothSearch";
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
public Toolbar toolbar;
//public static Handler UIHandler;
private static final int REQUEST_ENABLE_BT = 1234;
//public static final String EXTRAS_TARGET_ACTIVITY = "extrasTargetActivity";
//private static final String JAALEE_BEACON_PROXIMITY_UUID = "EBEFD083-70A2-47C8-9837-E7B5634DF524";//Jaalee BEACON Default UUID
// private static final Region ALL_BEACONS_REGION = new Region("rid", null, null, null);
//public static final String EXTRAS_BEACON = "extrasBeacon";
public BeaconManager beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());
private ArrayList<Beacon> arrayL = new ArrayList<Beacon>();
private BeaconServiceUtility beaconUtill = null;
private BeaconAdapter adapterr;
public ListView list;
private LayoutInflater inflater;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
viewadapter = new ViewPagerAdapter(getSupportFragmentManager());
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Bluetooth Devices");
//Set up the View Pager with the View page adapter
myViewPager = (ViewPager)findViewById(R.id.viewpager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(myViewPager);
//tabLayout.setVisibility(View.GONE);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_popup_sync_24);
setupViewPager(myViewPager);
setSupportActionBar(toolbar);
//viewPager.setAdapter(adapter);
myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0: fab.show();
break;
case 1: fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
drawer.closeDrawer(Gravity.LEFT);
}
});
adapterr = new BeaconAdapter();
list = findViewById(R.id.beaconlist);
list.setAdapter(adapterr);
//list.setOnItemClickListener(createOnItemClickListener());
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new blueToothSearch.bluetooth(), "Available Devices");
adapter.addFragment(new bluetoothProperties(), "Device Properties");
viewPager.setAdapter(adapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
connectToService();
}else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show();
getSupportActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService(){
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
}
/**
private AdapterView.OnItemClickListener createOnItemClickListener(){
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null){
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(blueToothSearch.this, clazz );
Beacon temp = adapterr.getItem(pos);
intent.putExtra(EXTRAS_BEACON, temp);
if(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY).contains("com.example.admin.paniccenter.CharacteristicsDemoActivity"))
{
startActivity(intent);
// if (temp.getProximityUUID().equalsIgnoreCase(JAALEE_BEACON_PROXIMITY_UUID)) {
// startActivity(intent);
// }
// else
// {
// ListBeaconsActivity.this.runOnUiThread(new Runnable()
//{
// public void run()
// {
//Toast.makeText(ListBeaconsActivity.this, "Current Beacon is in Non-Connectable mode", Toast.LENGTH_LONG).show();
// }
// });
// }
}
else
{
startActivity(intent);
}
}catch (ClassNotFoundException e){
Log.e(TAG, "Finding class by name failed", e);
}
}
}
};
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.scan_menu, menu);
MenuItem refreshItem = menu.findItem(R.id.refresh);
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
beaconUtill.onStart(beaconManager, this);
}
#Override
public void onStop() {
beaconUtill.onStop(beaconManager, this);
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBeaconServiceConnect() {
getSupportActionBar().setSubtitle("Scanning...");
Toast.makeText(this, "Scanning for devices", Toast.LENGTH_LONG).show();
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
arrayL.clear();
arrayL.addAll((ArrayList<Beacon>) beacons);
adapterr.notifyDataSetChanged();
}
});
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.e("BeaconDetactorService", "didEnterRegion");
}
#Override
public void didExitRegion(Region region) {
Log.e("BeaconDetactorService", "didExitRegion");
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
Log.e("BeaconDetactorService", "didDetermineStateForRegion");
}
});
connectToService();
}
public static class bluetooth extends Fragment {
private static final String TAG = "bluetooth";
private int position;
private TextView textv;
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
private FragmentActivity myContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
//hideAction = (HideActionBar)getContext();
myContext = (FragmentActivity)getContext();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//position = getArguments().getInt("pos");
//toolbar.getMenu().clear();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
View view = inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
//TextView text = (TextView)getActivity().findViewById(R.id.view);
//text.setText("i am the real text ");
//hideAction.customBlueToothToolbar();
//FloatingActionButton fl = (FloatingActionButton)getActivity().findViewById(R.id.fab);
//fl.setImageResource(R.drawable.ic_popup_sync_24);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
public class BeaconAdapter extends BaseAdapter {
private ArrayList<Beacon> beacons;
#Override
public int getCount() {
return arrayL.size();
}
#Override
public Beacon getItem(int arg0) {
return arrayL.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
holder = new ViewHolder(convertView = inflater.inflate(R.layout.tupple_monitoring, null));
}
if (beacons.get(position).getParserIdentifier() != null)
holder.beacon_uuid.setText("UUID: " + arrayL.get(position).getParserIdentifier());
holder.beacon_major.setText("Major: " + arrayL.get(position).getBeaconTypeCode());
holder.beacon_minor.setText(", Minor: " + arrayL.get(position).getBluetoothName());
holder.beacon_proximity.setText("Proximity: " + arrayL.get(position).getDistance());
holder.beacon_rssi.setText(", Rssi: " + arrayL.get(position).getRssi());
holder.beacon_txpower.setText(", TxPower: " + arrayL.get(position).getTxPower());
holder.beacon_range.setText("" + arrayL.get(position).getExtraDataFields());
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
private TextView beacon_uuid;
private TextView beacon_major;
private TextView beacon_minor;
private TextView beacon_proximity;
private TextView beacon_rssi;
private TextView beacon_txpower;
private TextView beacon_range;
public ViewHolder(View view) {
beacon_uuid = (TextView) view.findViewById(R.id.BEACON_uuid);
beacon_major = (TextView) view.findViewById(R.id.BEACON_major);
beacon_minor = (TextView) view.findViewById(R.id.BEACON_minor);
beacon_proximity = (TextView) view.findViewById(R.id.BEACON_proximity);
beacon_rssi = (TextView) view.findViewById(R.id.BEACON_rssi);
beacon_txpower = (TextView) view.findViewById(R.id.BEACON_txpower);
beacon_range = (TextView) view.findViewById(R.id.BEACON_range);
view.setTag(this);
}
}
}
I am using a BeaconManager class to range and scan my beacons, the library is from package org.altbeacon.beacon

Exception when Intent Data to another Activity android.content.Context.getPackageName()

Hello guys iam trying to get Data to putExtra => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity it Gives me this Exception that
java.lang.String android.content.Context.getPackageName()'
so i tried to Enter the Context class i found it too many Errors cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object inside the Adapter
tinyDB = new TinyDB(mContext);
the program Crashed and Gives Me this Exception
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err: at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4910)
at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22465)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
i tried to Fix that but still cant handle the Context problem
Here is my Adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {
public EventsAdapter(List<EventsModel> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
private List<EventsModel> list;
private Context mContext;
FirebaseAuth mAuth;
DatabaseReference dbRef;
#NonNull
#Override
public EventsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.events_row_item, parent, false);
EventsHolder holder = new EventsHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final EventsHolder holder, int position) {
final EventsModel listy = list.get(position);
holder.eventTitle.setText(listy.getTitle());
holder.eventDate.setText(listy.getEventDate());
holder.eventCosts.setText("Event Costs " + listy.getCosts());
Picasso.get()
.load(listy.getEventImage())
.fit()
.centerCrop()
.placeholder(R.drawable.gradients_card)
.into(holder.eventImage);
holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, ShowActivityEvents.class);
intent.putExtra("EventImage", listy.getEventImage());
intent.putExtra("EventTitle", listy.getTitle());
intent.putExtra("EventDate", listy.getEventDate());
intent.putExtra("EventCosts", listy.getCosts());
intent.putExtra("EventDescription", listy.getDescription());
intent.putExtra("eventID", listy.getPostID());
mContext.startActivity(intent);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
String userName = mAuth.getCurrentUser().getDisplayName();
String postID = listy.getPostID();
dbRef.child("Events").child(postID).child("Views").push().setValue(userName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String postID = listy.getPostID();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long ViewsCount = dataSnapshot.getChildrenCount();
holder.txtViews.setText(String.valueOf(ViewsCount));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class EventsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.EventImageCard)
ImageView eventImage;
#BindView(R.id.txtEventTitle)
TextView eventTitle;
#BindView(R.id.txtEventDate)
TextView eventDate;
#BindView(R.id.txtEventCosts)
TextView eventCosts;
#BindView(R.id.cardView_EventsCard)
CardView cardViewEvents;
#BindView(R.id.txtEventsViews) TextView txtViews;
public EventsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
here is my Activity which receive the Extras from the Adapter
public class ShowActivityEvents extends AppCompatActivity {
DatabaseReference dbRef;
FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
checkIfUserAlreadyAccepttheEvent();
}
private void checkIfUserAlreadyAccepttheEvent() {
final String postID = getIntent().getExtras().getString("eventID");
final String UserID = mAuth.getCurrentUser().getUid();
dbRef.child(postID).child("PeopleComing")
.addListenerForSingleValueEvent(new ValueEventListener() {
public static final String TAG = "ShowEvents";
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildAdded: " + dataSnapshot);
String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
txtPeopleComing.setText( peopleCount + " People Comming");
if (dataSnapshot.child(UserID).exists()) {
btnIamIn.setEnabled(false);
} else {
btnIamIn.setEnabled(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();
}
});
}
#BindView(R.id.btnIamIn)
Button btnIamIn;
#BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;
#BindView(R.id.imgEventPost)
ImageView imgEvent;
#BindView(R.id.txtEventTitle) TextView txtEventTitle;
#BindView(R.id.txtEventDescription) TextView txtEventDescription;
#BindView(R.id.txtEventCost) TextView txtEventCost;
#BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events2);
ButterKnife.bind(this);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
try {
loadDataFromAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadDataFromAdapter() {
String Image = getIntent().getExtras().getString("EventImage");
String Title = getIntent().getExtras().getString("EventTitle");
String Date = getIntent().getExtras().getString("EventDate");
String Costs = getIntent().getExtras().getString("EventCosts");
String Description = getIntent().getExtras().getString("EventDescription");
GlideApp.with(this)
.load(Image)
.fitCenter()
.into(imgEvent);
txtEventTitle.setText(Title);
txtEventDescription.setText(Description);
txtEventDate.setText(Date);
txtEventCost.setText(Costs);
}
#OnClick(R.id.btnIamIn) public void addPersonToEvent(){
String UserName = mAuth.getCurrentUser().getDisplayName();
String userID = mAuth.getCurrentUser().getUid();
String postID = getIntent().getExtras().getString("eventID");
dbRef.child(postID)
.child("PeopleComing").setValue(UserName);
btnIamIn.setEnabled(false);
}
}
Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);
Fragment
adapter = new EventsAdapter(myList,getActivity());
Or another way
#Override
public void onClick(View v) {
v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}

Can't back to previous activity

I need to help. I tried to back to previous activity, but when I click arrow button (action bar) it show errors. Can someone help me .. please!
Thank's before for your answers
This is my codes:
First, I get data in KitabActivity (so this is the first activity):
KitabActivity:
public class KitabActivity extends AppCompatActivity {
private List<Kitab> kitabList;
private RecyclerView recyclerView;
private KitabAdapter kitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbar;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kitab);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Kitab Hadits");
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_kitab);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
kitabList = new ArrayList<>();
getDataKitab();
}
private void getDataKitab() {
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigKitab.DATA_URL_KITAB, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(KitabActivity.this, "Gagal koneksi ke server!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
Kitab kitab = new Kitab();
JSONObject jsonObject = null;
try{
jsonObject = jsonArray.getJSONObject(i);
kitab.setId_kitab(jsonObject.getString(ConfigKitab.TAG_ID_KITAB));
kitab.setNama_kitab(jsonObject.getString(ConfigKitab.TAG_NAMA_KITAB));
}catch(JSONException e){
e.printStackTrace();
}
kitabList.add(kitab);
}
kitabAdapter = new KitabAdapter(kitabList,this);
recyclerView.setAdapter(kitabAdapter);
}
}
In KitabAdapter, I pass KEY_ID to BabKitabActivity:
This is KitabAdapter:
public class KitabAdapter extends RecyclerView.Adapter<KitabVH> {
private Context context;
List<Kitab> kitabList;
public KitabAdapter(List<Kitab> kitabList, Context context){
super();
this.kitabList = kitabList;
this.context = context;
}
#Override
public KitabVH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_kitab,parent,false);
return new KitabVH(view);
}
#Override
public void onBindViewHolder(KitabVH holder, int position) {
final Kitab kitab = kitabList.get(position);
holder.bind(kitab);
holder.cv_kitab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), BabKitabActivity.class);
intent.putExtra("KEY_ID",kitab.getId_kitab());
intent.putExtra("KEY_NAMA",kitab.getNama_kitab());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return kitabList.size();
}
}
BabKitabActivity:
public class BabKitabActivity extends AppCompatActivity {
private List<BabKitab> babKitabList;
private RecyclerView recyclerView;
private BabKitabAdapter babKitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbarBab;
private ActionBar actionBar;
private String id_kitab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bab_kitab);
toolbarBab = (Toolbar) findViewById(R.id.toolbarBab);
toolbarBab.setTitle(getIntent().getExtras().getString("KEY_NAMA"));
setSupportActionBar(toolbarBab);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_bab);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
babKitabList = new ArrayList<>();
getDataBab();
}
private void getDataBab() {
id_kitab = getIntent().getExtras().getString("KEY_ID");
String url = ConfigBabKitab.DATA_URL_BAB+id_kitab;
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(BabKitabActivity.this, "Gagal Koneksi ke Server!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray response) {
for(int i=0;i<response.length();i++){
BabKitab babKitab = new BabKitab();
JSONObject obj = null;
try{
obj = response.getJSONObject(i);
babKitab.setId_bab_kitab(obj.getString(ConfigBabKitab.TAG_ID_BAB));
babKitab.setNomor_bab(obj.getString(ConfigBabKitab.TAG_NOMOR_BAB));
babKitab.setNama_bab(obj.getString(ConfigBabKitab.TAG_NAMA_BAB));
babKitab.setPenjelasan(obj.getString(ConfigBabKitab.TAG_PENJELASAN));
}catch(JSONException e){
e.printStackTrace();
}
babKitabList.add(babKitab);
}
babKitabAdapter = new BabKitabAdapter(babKitabList,this);
recyclerView.setAdapter(babKitabAdapter);
}
}
DetailActivity:
public class DetailActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<DetailHadits> detailHaditsList;
private DetailAdapter detailAdapter;
private String id_bab_kitab;
private TextView tv_penjelasan;
private String penjelasan;
private CardView cv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDetail);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
cv = (CardView) findViewById(R.id.cv);
tv_penjelasan = (TextView) findViewById(R.id.tv_penjelasan);
//cv.setVisibility(View.GONE);
//tv_penjelasan.setVisibility(View.GONE);
penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");
tv_penjelasan.setText(penjelasan);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_detail);
//recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
detailHaditsList = new ArrayList<>();
getAyat();
}
private void getAyat() {
id_bab_kitab = getIntent().getExtras().getString("KEY_ID");
String url = ConfigDetail.DATA_URL_AYAT+id_bab_kitab;
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(DetailActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
DetailHadits detailHadits = new DetailHadits();
JSONObject obj = null;
try{
obj = jsonArray.getJSONObject(i);
detailHadits.setUrlGambarAyat(obj.getString(ConfigDetail.TAG_GAMBAR));
detailHadits.setTerjemahanAyat(obj.getString(ConfigDetail.TAG_TERJEMAHAN));
}catch(JSONException e){
e.printStackTrace();
}
detailHaditsList.add(detailHadits);
}
detailAdapter = new DetailAdapter(detailHaditsList,this);
recyclerView.setAdapter(detailAdapter);
}
}
and this is the log cat:
FATAL EXCEPTION: main
Process: id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits, PID: 15228
java.lang.RuntimeException: Unable to start activity ComponentInfo{id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits/id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
thank's in advance ;)
So, in my case BabKitabActivity can load data if there is a KEY_ID from KitabActivity (i guess).
What I want is just go back to previous activity (in this case to BabKitabActivity) without getting KEY_ID again.
It work with button back in emulator or smartphone, but it doesn't work with arrow button in actionbar, what should I do?
before getIntent().getExtras() check its null or not
Bundle extras = getIntent().getExtras();
if (extras != null) {
penjelasan = extras.getString("KEY_PENJELASAN");
}
something like
if (extras != null) {
id_bab_kitab = extras.getString("KEY_ID");
}
Unable to start activity ComponentInfo{id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits/id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.os.Bundle.getString(java.lang.String)' on a
null object reference
Issue is in your BatkitabActivity. You are getting string from intent which is null. Before getting string value, you can check if intent is null or not.
Bundle extras = getIntent().getExtras();
if (extras != null) {
....
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");
you can get the Bundle's data from getIntent().getExtras(), but you get null, so you got the NullPointerException, that make a crash in your app.

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Collection

I want to add search functionality in my apps. Mainly it's retrieve json data into a List.
Here is my code
MainActivity main;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<WorldPopulation> arrayList;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
mPublisherInterstitialAd = new PublisherInterstitialAd(context);
mPublisherInterstitialAd.setAdUnitId("ca-app-pub-7500090319214897/8263070161");
mPublisherInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
}
});
return itemView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll((Collection<? extends HashMap<String, String>>) resultp);
} else {
for (HashMap<String, String> wp : (Collection<? extends HashMap<String, String>>) resultp) {
if (wp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(wp);
}
}
}
notifyDataSetChanged();
}
I got some error in this code.how can i solve it?
i am stack more than 15days. Help me out.
here is my error
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Collection
at com.sextech.noui.ListViewAdapter.filter(ListViewAdapter.java:154)
at com.sextech.noui.MainActivity$DownloadJSON$1.afterTextChanged(MainActivity.java:230)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7822)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9635)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:976)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:520)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:454)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:33)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:690)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:450)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:349)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:82)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Main Activity
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private AdView mAdView;
private InterstitialAd interstitial;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("")
.build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=AIzaSyAFfA9cCFpmsyK5byKaRWE_oQKjjsABuxI");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.vdoapps.banglatube")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
HashMap does not implement Collection. So you cannot type cast HashMap into a Collection.
In your case, the type cast is not needed. The resultp object of of type HashMap, and the data object is of type ArrayList<HashMap>, so you can simply do data.add(resultp)
For the loop, you don't need the loop at all.
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault()) .contains(charText)) {
data.add(resultp);
}

Categories