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;
};
Related
**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}
RETRIEVADATA CLASS
package com.dikolobe.salesagent;
public class RetrieveData extends AppCompatActivity implements View.OnClickListener,OnNoteClickListener{
private static final String TAG = "";
private FirebaseRecyclerAdapter<Product, ViewHolder> firebaseRecyclerAdapter;
//FirebaseRecyclerAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
ItemsAdapter itemsAdapter;
List<Product> productList=new ArrayList<>();
RecyclerView recyclerView;
TextView phone_num;
ViewHolder viewHolder;
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView img;
OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems= new ArrayList<>();
private List<Product> listItemsFull;
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
String imageUrl = null;
SearchView searchView;
//ImageView delete;
String productId;
String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_data);
// delete =findViewById(R.id.delete);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
searchView=findViewById(R.id.search);
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance().getReference()
.child("Items"),Product.class)
.build();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<Product>();
itemsAdapter = new ItemsAdapter(RetrieveData.this, productList,this,options);
recyclerView.setAdapter(itemsAdapter);
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Product product = dataSnapshot.getValue(Product.class);
productList.add(product);
itemsAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance()
.getReference().child("Items"), Product.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull com.dikolobe.salesagent.ViewHolder holder, final int
position, #NonNull Product product) {
}
#NonNull
#Override
public com.dikolobe.salesagent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.design_row_for_recyclerview, parent, false);
return new com.dikolobe.salesagent.ViewHolder(view,onNoteClickListener);
}
public void deleteProduct(int position) {
try{
FirebaseDatabase.getInstance().getReference().child("Items")
.child(getRef(position).getKey())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context,"Deleted succesfully",Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.e("error", e.getMessage());
}
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStop() {
super.onStop();
firebaseRecyclerAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
search_product(query);
// itemsAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search_product(newText);
//itemsAdapter.getFilter().filter(newText.toString());
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.add_product) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "post a product", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.tutorial) {
// startActivity(new Intent(this, AddRider.class));
// Toast.makeText(this,"Add a rider to an Event",Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.logOut) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "bye", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
ItemTouchHelper.SimpleCallback simpleCallback=new
ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, Re
cyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
removeItem((long) viewHolder.itemView.getTag());
productList.remove(viewHolder.getAdapterPosition());
itemsAdapter.notifyDataSetChanged();
}
private void removeItem(long id) {
}
};
private boolean updateItem(String seller, String description, String price,String location,String
phone,String productId,String image,String posted_date) {
//getting the specified product reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Items").child(productId);
//updating product
Product product = new Product(productId, seller,
description,price,phone,location,image,posted_date);
dR.setValue(product);
Toast.makeText(getApplicationContext(), "Product Updated", Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onNoteClick(final int position) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RetrieveData.this);
dialog.setTitle("Choose Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent update_activty = new Intent(getApplicationContext(),Update_Product.class);
startActivity(update_activty);
}
if (i==1){
Product product=productList.get(position);
productId =product.getProductId();
image =product.getImage();
final AlertDialog.Builder dialogdelete = new
AlertDialog.Builder(RetrieveData.this);
dialogdelete.setTitle("Warning");
dialogdelete.setMessage("Are You Sure You Want to Delete?");
dialogdelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Query mQuery = mRef.orderByChild("productId").equalTo(productId);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
Toast.makeText(RetrieveData.this,"deleted..!",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RetrieveData.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Query mPictureReference =
FirebaseDatabase.getInstance().getReference("Items").orderByChild("image").equalTo(image);
mPictureReference.getRef().removeValue().addOnSuccessListener(new
OnSuccessListener() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RetrieveData.this,"Image
deleted",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RetrieveData.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
dialogdelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogdelete.show();
}
}
});
dialog.show();
// Toast.makeText(getApplicationContext(),"cliked",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
}
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
}
ADAPTER CLASS
package com.dikolobe.salesagent;
public class ItemsAdapter extends RecyclerView.Adapter implements Filterable {
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
private OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems;
private List<Product> listItemsFull;
private Product product;
FirebaseRecyclerOptions<Product> options;
String imageUrl = null;
public ItemsAdapter(Context context, List<Product> listItems,OnNoteClickListener
onNoteClickListener,FirebaseRecyclerOptions options) {
this.context = context;
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.onNoteClickListener = onNoteClickListener;
this.options=options;
}
public ItemsAdapter(FirebaseRecyclerOptions<Product> options) {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.design_row_for_recyclerview,parent,false);
return new ViewHolder(v,onNoteClickListener);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
product = listItems.get(position);
holder.seller.setText(listItems.get(position).getSeller());
holder.desc.setText(listItems.get(position).getDescription());
holder.price.setText(listItems.get(position).getPrice());
holder.location.setText(listItems.get(position).getLocation());
holder.phone.setText(listItems.get(position).getPhone());
holder.time.setText((CharSequence) listItems.get(position).getPosted_date());
holder.progress_Bar = new ProgressBar(context);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
holder.progressBar.setProgress(progressStatus);
holder.textView.setText(progressStatus+"/"+holder.progressBar.getMax());
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
imageUrl = product.getImage();
Picasso.get().load(imageUrl).into(holder.imageView, new Callback() {
#Override
public void onSuccess() {
holder.image_layout.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.phoneTv){
String phoneNumber = product.getPhone();
String message = "I am interested";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context,"Interest message sent successfully",
Toast.LENGTH_LONG).show();
}
}
});
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.call){
String phoneNumber = product.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
context.startActivity(intent);
}
}
}); }
#Override
public int getItemCount() {
return listItems.size();
}
#Override
public Filter getFilter() {
return filterProducts;
}
private Filter filterProducts = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
///*to delete*/String search_text = constraint.toString().toLowerCase();
List<Product> productFiltrate = new ArrayList<>();
if (constraint.length()==0 ){
productFiltrate.addAll(listItemsFull);
}else
{
String pattern = constraint.toString().toLowerCase().trim();
for (Product product:listItemsFull){
if(product.getSeller().toLowerCase().contains(pattern)){
productFiltrate.add(product);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = productFiltrate;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
INSERT DATA/MAIN_ACTIVITY
package com.dikolobe.salesagent;
public class MainActivity extends AppCompatActivity {
FirebaseRecyclerAdapter firebaseRecyclerAdapter;
ItemsAdapter itemsAdapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
EditText seller_name,desc,price,location,phone;
Button btnInsert,list;
ImageButton imageButton,take_Photo;
ProgressBar progressBar;
private ProgressDialog mProgress;
Uri imageUri = null;
final int REQUEST_CODE_IMAGE=999;
static final int REQUEST_IMAGE_CAPTURE = 1;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ViewHolder holder;
FrameLayout image_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seller_name = findViewById(R.id.seller_nameEt);
desc = findViewById(R.id.descEt);
price = findViewById(R.id.priceEt);
location = findViewById(R.id.locationEt);
phone = findViewById(R.id.phoneEt);
btnInsert = findViewById(R.id.save);
//list = findViewById(R.id.list);
imageButton = findViewById(R.id.imageButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
image_layout = (FrameLayout) findViewById(R.id.layout_image);
take_Photo = (ImageButton) findViewById(R.id.take_pic);
take_Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.take_pic){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
});
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE);
}
});
progressBar = new ProgressBar(MainActivity.this);
image_layout.setVisibility(View.INVISIBLE);
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_layout.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
final String seller = seller_name.getText().toString().trim();
final String fn = desc.getText().toString().trim();
final String ln = price.getText().toString().trim();
final String place = location.getText().toString().trim();
final String phon = phone.getText().toString().trim();
final String id = mRef.push().getKey();
if (!(seller.isEmpty() && fn.isEmpty() && ln.isEmpty() && place.isEmpty() &&
phon.isEmpty() && imageUri!=null)){
StorageReference filepath =
mStorage.getReference().child("images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image_layout.setVisibility(View.INVISIBLE);
Task<Uri> downloadUrl =
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String t=task.getResult().toString();
final DatabaseReference newPost=mRef.push();
newPost.child("seller").setValue(seller);
newPost.child("description").setValue(fn);
newPost.child("price").setValue(ln);
newPost.child("location").setValue(place);
newPost.child("phone").setValue(phon);
newPost.child("productId").setValue(id);
newPost.child("image").setValue(task.getResult().toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
newPost.child("posted_date").setValue(strDate);
Toast.makeText(MainActivity.this,"successfully uploaded",
Toast.LENGTH_SHORT).show();
seller_name.setText("");
desc.setText("");
price.setText("");
location.setText("");
phone.setText("");
imageButton.setImageURI(null);
goToRetrieveDataClass();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed to
upload..!",Toast.LENGTH_LONG).show();
}
});
}
});
}else Toast.makeText(MainActivity.this,"Please write all your
details..!",Toast.LENGTH_LONG).show();
}
});
if (!hasCamera())
take_Photo.setEnabled(false);
}
#Override
protected void onStart() {
super.onStart();
// firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
// firebaseRecyclerAdapter.stopListening();
}
private Boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
if (requestCode == REQUEST_CODE_IMAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE_IMAGE);
} else {
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
imageUri = data.getData();
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(this);
imageButton.setImageURI(imageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode,data);
}
}
Here is my full java class code.
It is showing null pointer exception. I have also add logcat screen shot. I am trying to solve this problem, but no way.Please help me if possible.
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> implements Filterable {
// Load Settings
private AppPreferences appPreferences;
// AppAdapter variables
private List<AppInfo> appList;
private List<AppInfo> appListSearch;
private Context context;
public AppAdapter(List<AppInfo> appList, Context context) {
this.appList = appList;
this.context = context;
this.appPreferences = SystemInfoManager.getAppPreferences();
}
#Override
public int getItemCount() {
return appList.size();
}
public void clear() {
appList.clear();
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(AppViewHolder appViewHolder, int i) {
AppInfo appInfo = appList.get(i);
appViewHolder.vName.setText(appInfo.getName());
appViewHolder.vApk.setText(appInfo.getAPK());
appViewHolder.vIcon.setImageDrawable(appInfo.getIcon());
setButtonEvents(appViewHolder, appInfo);
}
private void setButtonEvents(AppViewHolder appViewHolder, final AppInfo appInfo) {
ButtonFlat appAbout = appViewHolder.vAbout;
ButtonFlat appShare = appViewHolder.vShare;
final ImageView appIcon = appViewHolder.vIcon;
final CardView cardView = appViewHolder.vCard;
appAbout.setBackgroundColor(Color.BLUE);
appShare.setBackgroundColor(Color.BLUE);
appAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Activity activity = (Activity) context;
Intent intent = new Intent(context, AppActivity.class);
intent.putExtra("app_name", appInfo.getName());
intent.putExtra("app_apk", appInfo.getAPK());
intent.putExtra("app_version", appInfo.getVersion());
intent.putExtra("app_source", appInfo.getSource());
intent.putExtra("app_data", appInfo.getData());
Bitmap bitmap = ((BitmapDrawable) appInfo.getIcon()).getBitmap();
intent.putExtra("app_icon", bitmap);
intent.putExtra("app_isSystem", appInfo.isSystem());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String transitionName = context.getResources().getString(R.string.transition_app_icon);
ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, appIcon, transitionName);
context.startActivity(intent, transitionActivityOptions.toBundle());
} else {
context.startActivity(intent);
activity.overridePendingTransition(R.anim.slide_in_right, R.anim.fade_back);
}
}
});
appShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UtilsApp.copyFile(appInfo);
Intent shareIntent = UtilsApp.getShareIntent(UtilsApp.getOutputFilename(appInfo));
context.startActivity(Intent.createChooser(shareIntent,
String.format(context.getResources().getString(R.string.send_to), appInfo.getName())));
}
});
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Activity activity = (Activity) context;
Intent intent = new Intent(context, AppActivity.class);
intent.putExtra("app_name", appInfo.getName());
intent.putExtra("app_apk", appInfo.getAPK());
intent.putExtra("app_version", appInfo.getVersion());
intent.putExtra("app_source", appInfo.getSource());
intent.putExtra("app_data", appInfo.getData());
Bitmap bitmap = ((BitmapDrawable) appInfo.getIcon()).getBitmap();
intent.putExtra("app_icon", bitmap);
intent.putExtra("app_isSystem", appInfo.isSystem());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String transitionName = context.getResources().getString(R.string.transition_app_icon);
ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, appIcon, transitionName);
context.startActivity(intent, transitionActivityOptions.toBundle());
} else {
context.startActivity(intent);
activity.overridePendingTransition(R.anim.slide_in_right, R.anim.fade_back);
}
}
});
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
final FilterResults oReturn = new FilterResults();
final List<AppInfo> results = new ArrayList<>();
if (appListSearch == null) {
appListSearch = appList;
}
if (charSequence != null) {
if (appListSearch != null && appListSearch.size() > 0) {
for (final AppInfo appInfo : appListSearch) {
if (appInfo.getName().toLowerCase().contains(charSequence.toString())) {
results.add(appInfo);
}
}
}
oReturn.values = results;
oReturn.count = results.size();
}
return oReturn;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if (filterResults.count > 0) {
InstalledAppsFragment.setResultsMessage(false);
} else {
InstalledAppsFragment.setResultsMessage(true);
}
appList = (ArrayList<AppInfo>) filterResults.values;
notifyDataSetChanged();
}
};
}
#Override
public AppViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View appAdapterView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.app_layout, viewGroup, false);
return new AppViewHolder(appAdapterView);
}
public static class AppViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vApk;
protected ImageView vIcon;
protected ButtonFlat vAbout;
protected ButtonFlat vShare;
protected CardView vCard;
public AppViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vApk = (TextView) v.findViewById(R.id.txtApk);
vIcon = (ImageView) v.findViewById(R.id.imgIcon);
vAbout = (ButtonFlat) v.findViewById(R.id.btnExtract);
vShare = (ButtonFlat) v.findViewById(R.id.btnShare);
vCard = (CardView) v.findViewById(R.id.app_card);
}
}
}
Here is the logcat message:
https://i.stack.imgur.com/vVOr7.jpg
Please give me some solution if possible.
I have used context.getBaseContext() but it also gave error.
Instead of parsing context to activity use getActiviy()
Intent intent = new Intent(getActivity(), AppActivity.class);
Try change this line
Instead
Intent intent = new Intent(context, AppActivity.class);
to
Intent intent = new Intent(YourActivityName.this, AppActivity.class);
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.
Situation :
I am working on Client-Server Communication.
When the users save the data (name of product, image, note), it should be transferred to the server side of the database.
But, I don't know how to code http Post request on the client side(Android).
MyWishlistsActivity.java
public class MyWishlistsActivity extends ListActivity {
SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
int[] to = new int[] { R.id.name };
custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
this.setListAdapter(custAdapter);
}
#Override
protected void onResume() {
super.onResume();
new GetContacts().execute((Object[]) null);
}
#SuppressWarnings("deprecation")
#Override
protected void onStop() {
Cursor cursor = custAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
custAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor> {
SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
return dbConnector.getAllWishlists();
}
#Override
protected void onPostExecute(Cursor result) {
custAdapter.changeCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
startActivity(addWishlists);
//Client-Server
Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
startActivity(addWishlists2);
//Client-Server End
return super.onOptionsItemSelected(item);
}
}
AddWishlists.java
public class AddEditWishlists extends Activity {
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_wishlist);
setUpViews();
}
private void setUpViews() {
inputname = (EditText) findViewById(R.id.inputname);
inputnote = (EditText) findViewById(R.id.inputnote);
inputphoto = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
inputname.setText(extras.getString("name"));
inputnote.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputname.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
saveContactTask.execute((Object[]) null);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditWishlists.this);
alert.setTitle("Error In Save Wish List");
alert.setMessage("You need to Enter Name of the Product");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveContact() {
if(yourSelectedImage!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=image;}
SQLiteConnector sqlCon = new SQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
}
else {
sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
inputphoto.setImageBitmap(yourSelectedImage);
}
}
}
}
ViewWishlist.java
public class ViewWishlist extends Activity {
private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_wishlist);
setUpViews();
}
private void setUpViews() {
name = (TextView) findViewById(R.id.inputname);
note = (TextView) findViewById(R.id.inputnote);
photo = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
name.setText(extras.getString("name"));
note.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
backBtn=(Button)findViewById(R.id.back);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
CustomWishlistsAdapter.java
public class CustomWishlistsAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;
public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = inflator.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);
if (image != null) {
if (image.length > 3) {
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
final SQLiteConnector sqlCon = new SQLiteConnector(context);
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteWishlist(id);
Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
}
}
This is my code.
Please help me how to add http post request on this code..
And also the php on the Server side .
For the Android HttpPost (to send JSON serialized data to a server)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("url_of_the_server");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("note", note);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
//With response you can check the server return status code(to check if the request has been made correctly like so
StatusLine sLine = response.getStatusLine();
int statusCode = sLine.getStatusCode();
For more information on how to call a php web service there is a pretty nice tutorial that can be found here