I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time. But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. Please help me out. I am attaching the code snippets. I got stuck here.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
int status = 0 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
// Show menu icon
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/**
* Lets inflate the very first fragment
* Here , we are inflating the NewsFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
// mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
status = 1;
if (status == 1){
}
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sent){
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_draft) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_weather) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
startActivity(intent_four);
case R.id.search:
// hidetext();
Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void hidetext() {
//
// Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
// startActivity(i);
// }
}
TopNewsFragment
public class TopNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
Movie movie;
private ListView listView;
private CustomListAdapter adapter;
String imageURL = "", title = "", description = "";
public static final String KEY_ID = "news_id";
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
RequestQueue requestQueue;
public TopNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
intent.putExtra(KEY_ID, item.getNewsId());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0) {
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
title = movie.setTitle(homenews.getString("Title"));
description = movie.setDescription(homenews.getString("Description"));
movie.setDescription(homenews.getString("Description"));
imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
// System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
LatestNewsFragment.java
public class LatestNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// contacts JSONArray
private JSONArray users = null;
RequestQueue requestQueue;
public static final String KEY_HEADURL="news_url";
public static final String KEY_DETAILS="news_details";
public static final String KEY_TITLE = "news_title";
public LatestNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
// intent.putExtra("URL", movie.getThumbnailUrl());
// intent.putExtra("title", movie.getTitle());
// intent.putExtra("description", movie.getDescription());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
// JsonObjectRequest jsonObjectRequest =
#Override
public void onResponse(JSONObject response) {
try {
hidePDialog();
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0){
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:
public class MyApp extends Application {
private RequestQueue mRequestQueue;
private static MyApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApp getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Don't forget to add your application class to your manifest inside the activity tag:
<application
android:name=".MyApp"
Now you can put requests on that queue from your fragments:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Do something with error
}
});
//Put the actual request on the queue
MyApp.getInstance().addToRequestQueue(req);
Related
Everything works fine, except that when I try to search on my app, it crashes. The problem is in the method onQueryTextChange, please help me to fix it:
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private static final int REQUEST_CAMERA_PERMISSION = 200;
Button goSettings;
ListView listApps;
Context context;
Button go_AndroBooster,goPerms,lockAll,unlockAll,goLogs;
Intent i;
private AccountHeader headerResult = null;
private Drawer result = null;
private MiniDrawer miniResult = null;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
MaterialProgressBar loadingBar;
ColorManager colorManager;
RelativeLayout mainLayout;
ArrayList<ApplicationInfo> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
colorManager = new ColorManager(this);
setSupportActionBar(toolbar);
mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
packageManager = getPackageManager();
listApps = (ListView) findViewById(R.id.listApps);
go_AndroBooster = (Button) findViewById(R.id.go_booster);
goPerms = (Button) findViewById(R.id.goPerms);
lockAll = (Button) findViewById(R.id.lock_all);
unlockAll = (Button) findViewById(R.id.unlock_all);
loadingBar = (MaterialProgressBar) findViewById(R.id.loadingBar);
goLogs = (Button) findViewById(R.id.goLogs);
goSettings = (Button) findViewById(R.id.lockSettings);
listApps.setItemsCanFocus(true);
startLockService();
setSupportActionBar(toolbar);
//set the back arrow in the toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#25517d")));
final IProfile profile2 = new ProfileDrawerItem().withIcon(R.drawable.user_icon);
// Create the AccountHeader
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withTranslucentStatusBar(false)
.withHeaderBackground(R.drawable.header)
.addProfiles(profile2)
.build();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withDrawerLayout(R.layout.crossfade_material_drawer)
.withHasStableIds(true)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.Home).withIcon(R.drawable.homee).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.logs).withIcon(R.drawable.cleanapp).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.resetpass).withIcon(R.drawable.boost).withIdentifier(3),
new PrimaryDrawerItem().withName(R.string.language).withIcon(R.drawable.share).withIdentifier(4),
new PrimaryDrawerItem().withName(R.string.share).withIcon(R.drawable.rate).withIdentifier(6),
new PrimaryDrawerItem().withName(R.string.rate).withIcon(R.drawable.rate).withIdentifier(7)
// new DividerDrawerItem(),
// new SecondaryDrawerItem().withName(R.string.drawer_item_seventh).withIcon(FontAwesome.Icon.faw_github).withIdentifier(7).withSelectable(false)
) // add the items we want to use with our Drawer
.withSelectedItemByPosition(1)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (drawerItem.getIdentifier() == 1) {
// Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 2) {
i = new Intent(getApplicationContext(), LogsActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 3) {
i = new Intent(getApplicationContext(), SetLockTypeActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 4) {
LanguagesDialog languagesDialog = new LanguagesDialog();
languagesDialog.show(getFragmentManager(), "LanguagesDialogFragment");
} else if (drawerItem.getIdentifier() == 6) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id="
+ getPackageName());
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, getResources().getText(R.string.shareusing)));
result.closeDrawer();
}else if (drawerItem.getIdentifier() == 7) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName()));
startActivity(browserIntent);
result.closeDrawer();
}
//
//
return false;
}
})
.withSavedInstance(savedInstanceState)
.withShowDrawerOnFirstLaunch(false)
.build();
//get out our drawerLyout
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
//hook to the crossfade event
crossfadeDrawerLayout.withCrossfadeListener(new CrossfadeDrawerLayout.CrossfadeListener() {
#Override
public void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset) {
Log.e("CrossfadeDrawerLayout", "crossfade: " + currentSlidePercentage + " - " + slideOffset);
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startReqUsageStat();
}
}, 3000);
lockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.lockAllApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
unlockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.resetLockedApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
goPerms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RequestPermission.class);
startActivity(i);
}
});
goLogs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LogsActivity.class);
startActivity(i);
}
});
go_AndroBooster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startApplication("");
}
});
goSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
finish();
}
});
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
new LoadApplications().execute();
}
}, 1500);
new Thread(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private void startLockService() {
if (!isMyServiceRunning(LockService.class)){
context.startService(new Intent(context, LockService.class));
}
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
private void startReqUsageStat(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission()){
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Toast.makeText(context,getString(R.string.please_give_usage_Stats),Toast.LENGTH_LONG).show();
}
}
} public boolean checkUsageStatsPermission(){
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
return !queryUsageStats.isEmpty();
}
public void startApplication(String packageName)
{
try
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info : resolveInfoList)
if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
{
launchComponent(info.activityInfo.packageName, info.activityInfo.name);
return;
}
showInMarket(packageName);
}
catch (Exception e)
{
showInMarket(packageName);
}
}
public String getPattern() {
File file = new File("/data/data/com.project.applocker/files/pattern");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
Log.d("okuma hatası", "no 1");
}
return text.toString();
}
private void launchComponent(String packageName, String name)
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(packageName, name));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showInMarket(String packageName)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final List<ApplicationInfo> appsList = context.getPackageManager().getInstalledApplications(0);
final ApplicationInfo data = appsList.get(i);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.performClick();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
private class LoadApplications extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
if(!isMyServiceRunning(LockService.class)){
startLockService();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
listApps.setAdapter(listadaptor);
listApps.setOnItemClickListener(MainActivity.this);
loadingBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
loadingBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
startLockService();
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (!info.packageName.equals("com.google.android.googlequicksearchbox")) {
if (!info.packageName.equals("com.project.applocker")) {
if (!info.packageName.contains("launcher3")) {
if (!info.packageName.contains("launcher")) {//com.google.android.googlequicksearchbox
if (!info.packageName.contains("trebuchet")) {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
}
Adapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
List<String> allAppList = null;
List<String> lockedAppList = null;
ColorManager colorManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appList) {
super(context, textViewResourceId, appList);
this.context = context;
allAppList = new ArrayList<String>();
colorManager = new ColorManager(context);
lockedAppList = new ArrayList<String>();
this.appsList = appList;
packageManager = context.getPackageManager();
preferences=context.getSharedPreferences("chosen_apps", context.MODE_PRIVATE);
Collections.sort(appsList, new ApplicationInfo.DisplayNameComparator(packageManager));
editor = preferences.edit();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.app_list_item, null);
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
CardView cardViewApps = (CardView) view.findViewById(R.id.cardViewApps);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
if(preferences.getBoolean(data.packageName,false)){
lockApp.setChecked(true);
}
else{
lockApp.setChecked(false);
}
lockApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.stopService(new Intent(context, LockService.class));
if (lockApp.isChecked()){
Log.d("tıklanmış",""+data.packageName);
editor.putBoolean(data.packageName,true).apply();
}
if (!lockApp.isChecked()){
Log.d("silinmiş",""+data.packageName);
editor.putBoolean(data.packageName,false).apply();
}
context.startService(new Intent(context, LockService.class));
}
});
}
return view;
}
private void startLockService() {
context.startService(new Intent(context, LockService.class));
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
}
The problem is here:
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
I think your method should be like below
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
}
if(templist != null && templist.size() > 0){}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,templist);
listApps.setAdapter(adapter);
}else{
listApps.setAdapter(null);
}
return true;
};
I have created a Custom Listview that will display area list from my database but sometimes the data won't display. After staying in the activity for a couple of seconds and restarting the activity again it will display the list. Here is my code can you check this out ? If see what's the problem. Thanks!
AreaListActivity.java
private ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setupActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
setupList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Only if you need to restore open/close state when
// the orientation is changed
if (adapter != null) {
adapter.saveStates(outState);
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Only if you need to restore open/close state when
// the orientation is changed
if (adapter != null) {
adapter.restoreStates(savedInstanceState);
}
}
private void setupList() {
ListView listView = (ListView) findViewById(R.id.list_view);
adapter = new ListAdapter(this, createList());
listView.setAdapter(adapter);
}
private List<String> createList() {
final List<String> list = new ArrayList<>();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
GetAreaListRequest registerRequest = new GetAreaListRequest("True", responseListener);
RequestQueue queue = Volley.newRequestQueue(AreaListActivity.this);
queue.add(registerRequest);
return list;
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
GetAreaListRequest.java
public class GetAreaListRequest extends StringRequest {
private static final String GET_AREA_LIST_URL = "http://192.168.1.7:8080/smsams/get_area_list.php";
private Map<String, String> params;
public GetAreaListRequest(String get_area_status, Response.Listener<String> listener) {
super(Method.POST, GET_AREA_LIST_URL, listener, null);
params = new HashMap<>();
params.put("get_area_status", get_area_status);
}
#Override
public Map<String, String> getParams() {
return params;
}
ListAdapter.java
class ListAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final ViewBinderHelper binderHelper;
private Context context;
ListAdapter(Context context, List<String> objects) {
super(context, R.layout.row_list, objects);
mInflater = LayoutInflater.from(context);
binderHelper = new ViewBinderHelper();
this.context = context;
// uncomment if you want to open only one row at a time
// binderHelper.setOpenOnlyOne(true);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_list, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.text);
holder.statView = convertView.findViewById(R.id.statistic_layout);
holder.mapView = convertView.findViewById(R.id.map_layout);
holder.infoView = convertView.findViewById(R.id.info_layout);
holder.swipeLayout = (SwipeRevealLayout) convertView.findViewById(R.id.swipe_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String item = getItem(position);
if (item != null) {
binderHelper.bind(holder.swipeLayout, item);
holder.textView.setText(item);
holder.statView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, StatisticActivity.class);
context.startActivity(i);
}
});
holder.mapView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, MapsActivity.class);
i.putExtra("soilArea", holder.mapView.toString());
context.startActivity(i);
}
});
holder.infoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, InfoViewActivity.class);
context.startActivity(i);
}
});
}
return convertView;
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {#link android.app.Activity#onSaveInstanceState(Bundle)}
*/
void saveStates(Bundle outState) {
binderHelper.saveStates(outState);
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {#link android.app.Activity#onRestoreInstanceState(Bundle)}
*/
void restoreStates(Bundle inState) {
binderHelper.restoreStates(inState);
}
private class ViewHolder {
TextView textView;
View statView;
View mapView;
View infoView;
SwipeRevealLayout swipeLayout;
}
Try this:
private List<String> list = new ArrayList<>();
private void setupList() {
ListView listView = (ListView) findViewById(R.id.list_view);
adapter = new ListAdapter(this, list);
listView.setAdapter(adapter);
}
private void createList() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
GetAreaListRequest registerRequest = new GetAreaListRequest("True", responseListener);
RequestQueue queue = Volley.newRequestQueue(AreaListActivity.this);
queue.add(registerRequest);
}
The network requests usually happens in an asynchronous way. So there is no specific time that the onResponse() gets called. So in your createList() method you initialised an empty arraylist and before the request produces the response(asynchronously calls onResponse) the list which contains no value is returned.
You can change your code something like this:
In createList():
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
adapter = new ListAdapter(this, list);
listView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
So here the adapter is set only after the data is pulled from the network.
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);
}
The Reason is the interstitial ad is on wrong way.
Can someone tell me Is there a problem with my interstitial?
Where to put it?
My code from where interstitial is:
public class ActivityMain extends Activity implements OnItemClickListener,
onWelComeButtonClickListener, OnClickListener {
MatrixCursor cursor;
ActionBar actionBar;
DrawerLayout dLayout;
ListView channelListView;
ChannelCustomAdapter adapter;
ActionBarDrawerToggle toggle;
CharSequence title;
Bundle bundle;
Menu menu;
RelativeLayout rlDrawerOpen;
Typeface selectFonts;
TextView tFacebook, tRateus;
AdRequest fullScreenAdRequest;
InterstitialAd fullScreenAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializer();
dLayout.setDrawerListener(toggle);
channelListView.setOnItemClickListener(this);
tFacebook.setOnClickListener(this);
tRateus.setOnClickListener(this);
enableAd();
}
private void enableAd() {
// adding full screen add
fullScreenAdd = new InterstitialAd(this);
fullScreenAdd.setAdUnitId("a151b7d316a5c1d");
fullScreenAdRequest = new AdRequest.Builder().build();
fullScreenAdd.loadAd(fullScreenAdRequest);
fullScreenAdd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.i("FullScreenAdd", "Loaded successfully");
fullScreenAdd.show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Log.i("FullScreenAdd", "failed to Load");
}
});
}
private void initializer() {
actionBar = getActionBar();
selectFonts = (Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Bold.ttf"));
dLayout = (DrawerLayout) findViewById(R.id.dl_drawerLayout);
rlDrawerOpen = (RelativeLayout) findViewById(R.id.rl_drawer_open);
channelListView = (ListView) findViewById(R.id.lv_channel_List);
title = getResources().getString(R.string.app_name);
tFacebook = (TextView) findViewById(R.id.tvFacbook);
tRateus = (TextView) findViewById(R.id.tvRateUs);
adapter = new ChannelCustomAdapter(this, GlobalData.getInstance()
.getArrChannels());
channelListView.setAdapter(adapter);
toggle = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_drawer,
R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView) {
setTitle("Select Channel");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
setTitle(title);
invalidateOptionsMenu();
}
};
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// use the query to search your data somehow
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG)
.show();
} else {
fragmentSelector();
}
}
private void fragmentSelector() {
bundle = getIntent().getBundleExtra("BUNDLE");
if (bundle == null) {
Fragment fr = new WelcomeFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
setTitle(title);
((WelcomeFragment) fr).setOnWelComeButtonClickListener(this);
} else {
selectItem(bundle.getInt("POS"));
setTitle(bundle.getString("NAME"));
}
}
public void selectItem(int position) {
Fragment fr = new RadioFragment();
bundle = new Bundle();
bundle.putString("URL",
GlobalData.getInstance().getArrChannels().get(position)
.getUrl());
bundle.putString("NAME",
GlobalData.getInstance().getArrChannels().get(position)
.getChannelName());
bundle.putInt("POS", position);
fr.setArguments(bundle);
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
title = GlobalData.getInstance().getArrChannels().get(position)
.getChannelName();
dLayout.closeDrawer(rlDrawerOpen);
}
#Override
public void setTitle(CharSequence title) {
actionBar.setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (getPositionfromString(query) != -1) {
Intent intent = new Intent(ActivityMain.this,
RadioService.class);
stopService(intent);
selectItem(getPositionfromString(query));
setTitle(query);
} else {
Toast.makeText(getApplicationContext(), "No channel found",
Toast.LENGTH_LONG).show();
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
String[] columnNames = {
"_id", "text"
};
cursor = new MatrixCursor(columnNames);
String[] temp = new String[2];
// int id = 0;
for (int i = 0; i < GlobalData.getInstance().getArrChannels()
.size(); i++) {
if (GlobalData.getInstance().getArrChannels().get(i)
.getChannelName().toLowerCase()
.contains(newText.toLowerCase())) {
temp[0] = Integer.toString(i);
temp[1] = GlobalData.getInstance().getArrChannels()
.get(i).getChannelName();
cursor.addRow(temp);
}
}
String[] from = {
"text"
};
int[] to = {
R.id.text
};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
ActivityMain.this, R.layout.search_item, cursor, from,
to, SimpleCursorAdapter.NO_SELECTION);
searchView.setSuggestionsAdapter(cursorAdapter);
return true;
}
});
searchView.setOnSuggestionListener(new OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(1), true);
return false;
}
});
return true;
}
private int getPositionfromString(String chn) {
for (int i = 0; i < GlobalData.getInstance().getArrChannels().size(); i++) {
if (chn.contentEquals(GlobalData.getInstance().getArrChannels()
.get(i).getChannelName())) {
return i;
}
}
return -1;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (toggle.onOptionsItemSelected(item)) return true;
if (item.getItemId() == R.id.search) return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.search).setVisible(!dLayout.isDrawerOpen(rlDrawerOpen));
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView <? > parent, View view, int position,
long id) {
Intent intent = new Intent(ActivityMain.this, RadioService.class);
stopService(intent);
selectItem(position);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onWelComeButtonClick() {
dLayout.openDrawer(rlDrawerOpen);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvFacbook:
Intent i = new Intent(ActivityMain.this, ShowFacebook.class);
startActivity(i);
break;
case R.id.tvRateUs:
String linkurl = "http://play.google.com/store/apps/details?id=com.global.danceradio";
if (linkurl != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, linkurl);
shareIntent.setType("text/plain");
startActivity(shareIntent);
} else {
Toast.makeText(getApplicationContext(), "Sharing failed...",
Toast.LENGTH_LONG).show();
}
break;
}
}
}
Here, everything looks normal. But there is no the rest of the code. Maybe you create an activity every second.
I would recommend you to write in support of the admob and clarify the issues. Maybe you're lucky and they will unblock you.
https://support.google.com/admob/answer/6201362?hl=en
Check admob support. they updated new photos for better explanation.
I'm trying to keep data(PID) from fragmentscan to fragment maintenance using arguments,
but the data always null in my Log.d("tag", "PID SCAN: " + data);
whats wrong with my arguments?
this is my code
public class FragmentScan extends Fragment {
TextView tvPid;
TextView txtName;
TextView txtPrice;
TextView txtDesc;
TextView txtSpec;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://10.0.3.2/skripsi/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_SPESIFICATION = "spesification";
// Progress Dialog
private static final String PID_KEY = "tvPid";
private static final String NAME_KEY = "tvName";
private static final String PRICE_KEY = "tvPrice";
private static final String DESCRIPTION_KEY = "tvDesc";
private static final String SPESIFICATION_KEY = "tvSpec";
private String mPid=null;
private String mName=null;
private String mPrice=null;
private String mDesc=null;
private String mSpec=null;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ZZZ", "ada di oncreateView");
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_layout_four, container, false);
tvPid = (TextView) rootView.findViewById(R.id.tvPid);
txtName = (TextView) rootView.findViewById(R.id.tvName);
txtPrice = (TextView) rootView.findViewById(R.id.tvPrice);
txtDesc = (TextView) rootView.findViewById(R.id.tvDesc);
txtSpec = (TextView) rootView.findViewById(R.id.tvSpec);
Btngetdata = (Button)rootView.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new FragmentMaintenance();
Bundle data = new Bundle();
data.putString("pid", mPid);
fragment.setArguments(data);
FragmentManager frgManager = getFragmentManager();
Log.d("tag", "PID SCAN: " + data);
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
}
});
Button scanBtn = (Button) rootView.findViewById(R.id.btnScan);
//in some trigger function e.g. button press within your code you should add:
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(), "ERROR:" + e, Toast.LENGTH_LONG).show();
}
}
});
if (savedInstanceState != null) {
Log.d("ZZZ", "ada di di dlm if saved");
mPid = savedInstanceState.getString(PID_KEY);
mName = savedInstanceState.getString(NAME_KEY);
mPrice = savedInstanceState.getString(PRICE_KEY);
mDesc = savedInstanceState.getString(DESCRIPTION_KEY);
mSpec = savedInstanceState.getString(SPESIFICATION_KEY);
tvPid.setText(mPid);
txtName.setText(mName);
txtPrice.setText(mPrice);
txtDesc.setText(mDesc);
txtSpec.setText(mSpec);
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d("ZZZ", "Ada di mainactivity");
if (requestCode == 0) {
TextView pid = (TextView) getActivity().findViewById(R.id.tvPid);
if (resultCode == Activity.RESULT_OK) {
pid.setText(intent.getStringExtra("SCAN_RESULT"));
new GetProductDetails(getActivity()).execute(pid.getText().toString());
} else if (resultCode == Activity.RESULT_CANCELED) {
pid.setText("Scan cancelled.");
}
}
}
class GetProductDetails extends AsyncTask<String, Void, String[]> {
/**
* Before starting background thread Show Progress Dialog
*/
private Context mContext;
public GetProductDetails(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
*/
protected String[] doInBackground(String... string) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", string[0]));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("ZZZ", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
String[] result = {Integer.toString(success), product.getString(TAG_NAME), > product.getString(TAG_PRICE),
product.getString(TAG_DESCRIPTION),
product.getString(TAG_SPESIFICATION)};
// // display product data in EditText
// txtName.setText(product.getString(TAG_NAME));
// txtPrice.setText(product.getString(TAG_PRICE));
// txtDesc.setText(product.getString(TAG_DESCRIPTION));
Log.d("ZZZ", result[0]);
return result;
} else {
Log.d("ZZZ", Integer.toString(success));
String[] result = {Integer.toString(success)};
return result;
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String[] results) {
// dismiss the dialog once got all details
pDialog.dismiss();
if (results[0] != null) {
Log.d("ZZZ", "SUCCESS" + results[0]);
if (results[0].matches("1")) {
Log.d("ZZZ", "SUCCESS " + results[0]);
TextView name = (TextView) getActivity().findViewById(R.id.tvName);
name.setText(results[1]);
TextView price = (TextView) getActivity().findViewById(R.id.tvPrice);
price.setText(results[2]);
TextView desc = (TextView) getActivity().findViewById(R.id.tvDesc);
desc.setText(results[3]);
TextView spec = (TextView) getActivity().findViewById(R.id.tvSpec);
spec.setText(results[4]);
} else if (results[0].matches("-1")) {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
} else{
Log.d("ZZZ", "UNKNOWN ERROR");
}
}
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(PID_KEY, tvPid.getText().toString());
savedInstanceState.putString(NAME_KEY, txtName.getText().toString());
savedInstanceState.putString(PRICE_KEY, txtPrice.getText().toString());
savedInstanceState.putString(DESCRIPTION_KEY, txtDesc.getText().toString());
savedInstanceState.putString(SPESIFICATION_KEY, txtSpec.getText().toString());
}
}
This my activity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
SharedPreferences preferences;
String pref;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = this.getSharedPreferences(Config.PREFERENCES, MODE_PRIVATE);
pref = preferences.getString(Config.SESSION,null);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Scanner", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Schedule", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Logout", R.drawable.ic_action_about));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new FragmentScan();
break;
case 1:
fragment = new FragmentSchedule();
break;
case 2:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 3:
logout();
Intent in = new Intent(this, LoginActivity.class);
startActivity(in);
finish();
return;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
SelectItem(position);
}
}
//In the same activity you’ll need the following to retrieve the results:
private void logout(){
//TODO delete cookie from db
SharedPreferences.Editor editor = preferences.edit();
editor.remove(Config.SESSION);
editor.remove(Config.USERNAME);
editor.commit();
}
i hope someone can help me to solving this,
thanks before.
I think it's supposed to be not null, perhaps you just didn't retrieve the value properly.
In your logging code, you used:
Log.d("tag", "PID SCAN: " + data);
but actually you stored the pid using:
data.putString("pid", mPid);
which means, you should use key pid to get the value from the bundle, like:
Log.d("tag", "PID SCAN: " + data.getString("pid"));
EDIT:
If it is a process ID you are trying to get, try to look at android.os.Process.myPid();
If pid is your own pre-defined variable (containing something else),
then you need to pass it when you create the fragment like the following:
fragment = new FragmentScan();
args.putString("pid", YOUR_TV_PID_VALUE);
and from the other side (FragmentScan), you can use getArguments() to get the Bundle, and from there, just use getString("pid").
UPDATE:
After reading your code more, it seems you got the cycle a little bit tangled.
but one quick suggestion is: why don't you try it like the following
data.putString("pid", tvPid.getText());
In you original code, your pid in savedInstanceState supposed to be exist after you perform click on scanBtn, finish/cancel the scanning. But I think your code flow is a little bit tangled.
Read here that onSaveInstanceState is called to retrieve per-instance state from an activity before being killed.
=> That means, before you open another intent (performed by scanBtn), onSaveInstanceState is called and storing empty value of the tvPid. And when the main intent is resumed, it gets that bundle which contains empty string of pid. But it should be "", not null.