Set ringtone based on position of selected list view item - java

I'm trying to save the selected sound as a ringtone/notification sound based on the position of the selected list view item but I'm having serious issues with finding relative tutorials (if any) for this. Below is my code so far but I want to achieve this in the simplest way/as less lines of code as possible hence for the sake of simplicity, I have used 1 context menu. Ideally
public void function1(int id){
}
is where the code would go for setting the ringtone and
public void function2(int id){
}
is where the code would go for setting the notification sound.
E.g. (trying to achieve this when setting a ringtone) Click & hold "chimes" list item > Context menu appears > Select "Set as Ringtone" context menu item > 'Phone ringtone' window appears (with "chimes" as one of the available options) > User clicks OK or Cancel > If the user clicks OK, return back to my app and show a toast notification ("Ringtone saved") OR If the user clicks Cancel, return back to my app and show a toast notification ("Ringtone not saved").
All help will be highly appreciated.
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private ListView mainList;
private MediaPlayer mp;
private final String[] listContent = {
"chimes", "chord", "ding", "notify",
"recycle", "ringin", "ring out","tada"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mainList = (ListView) findViewById(R.id.main_listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
mainList.setAdapter(adapter);
registerForContextMenu(this.mainList);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, "Action 1");
menu.add(0, v.getId(), 0, "Action 2");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle().equals("Action 1")){
function1(item.getItemId());
} else if (item.getTitle().equals("Action 2")){
function2(item.getItemId());
} else {
return false;
}
return true;
}
public void function1(int id){
}
public void function2(int id){
}
}

In order to set the ringtone or notification sound you use the RingToneManager.
Specifically you use
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
for setting default ringtone. And you use
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION, newUri);
for setting default notification sound.
This needs a URI (Uniform Resource Identifier) which is a not an integer or ItemId like the one your functions currently take.
From your sample code, there are a few possible options that could be taken.
The first is to pass in the title of the Ringtone into the function, as a string instead of the ID, and then call RingtoneManager.getCursor() in order to get a list of all possible ringtones and check each one to see if the titles match and if they do then you set the URI for the matching title.
The second is to make your list of choices based on the cursor of all available ringtones and the pass in the id, and get the URI using RingtoneManager.getRingtoneUri(id). One way of doing this is detailed at Using SimpleCursorAdapter to Display Ringtones from RingtoneManager in Android Using ListView Templates
The third is to use ACTION_RINGTONE_PICKER which has a relevant StackOverflow Question.

Sorry, this could have been a comment. I dont have enough permission to comment right now. And do let me know how this works out for u...
To get the ringtone picker,
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_NOTIFICATION);
startActivityForResult(intent,999);
Now override the onActivityResult() in the activity/fragment.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK
&& requestCode == 999)
if (data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) != null) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null) {
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION, uri);
}
}
}
}
Hope this works.... (And Upvote if useful)...

Related

how to fix "The value true assigned to "variable" is never used" in Android Studio?

I am making this eCommerce app,
And, i wanted this behaviour in it.
Which is-
At the opening, there will be pitures in the MainActivity.
And a search box.
When you click the picture it will take you to MainActivity2 and there is an ImageView in this activity which will change to become the same picture as the picture I clicked in MainActivity.
And
When you search something in the search box in the MainActivity,
if your searched text matches with the string object of the arraylist in the MainActivity2,
it will change the ImageView of MainActivity2 with the corresponding image of the string object of the arraylist.
I hope, i made minimum grammatical mistakes to make you understand my problem. 😅
Anyways,
For the first case-
I tried to make this work by using On touchListeners, Intenets and booleans.
As you can see in the code below,
touching my ImageView(iBtn1) will trigger Intent intent1, make boolean i1
=true and then send the boolean to next activity in the name "t1".
And ,
For the second case-
I tried using OnClickListeners, Intenets, arraylists and booleans.
First,
I changed the Edittext(input) into string.
For clicking the search Button(igo),
it will trigger Intent intent,
Then it will send the string Data of the input as "eText" and send boolean data x=true, as "x".
public class MainActivity extends AppCompatActivity {
EditText input;
ImageView iBtn1;
TextView tName, tPrice, tDescription;
ImageView iImage;
Button igo;
String eText;
boolean i1,x;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1=false;
x=false;
igo=findViewById(R.id.go);
iBtn1=findViewById(R.id.Btn1);
input=findViewById(R.id.edittext);
eText=input.getText().toString();
igo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x=true;
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("eText",eText);
intent.putExtra("x",x);
startActivity(intent);
}
});
iBtn1.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
iBtn1.setBackground(ContextCompat.getDrawable(getApplicationContext(),R.drawable.ectangle_31_1));
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
iBtn1.setBackground(ContextCompat.getDrawable(getApplicationContext(),R.drawable.ectangle_31));
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
i1=true;
Intent intent1=new Intent(MainActivity.this,MainActivity2.class);
intent1.putExtra("t1",i1);
startActivity(intent1);
v.performClick();
v.setPressed(false);
return false;
} else {
return false;
}
});
In the next activity-
For my first case-
My target ImageView is iImage.
But at first, what i did was, get the (boolean) data from the previous Intent intent1 to the current Intent I1.
Then i have declared a variable(x1) containing the value of that boolean data.
Then i have implemented an if condition,
If x1 is true, it will change the image resource of the ImageView iImage.
Else, nothing happens.
And, for my 2nd case-
I have this arraylist made up. It contained string data as xName and imageId as xImageId.
Anyways,
First i got the string data from "eText" and boolean data using getIntent.
Then implementating if condition, i tried to compare the string data with the string of arraylist.
If it is equal.
Then i told the programm to change the ImageView just like the case-1
And, i got the data
public class MainActivity2 extends AppCompatActivity {
String eName;
boolean bx;
ImageView iImage;
TextView iname;
Intent I1,intent;
ArrayList<x> xList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
iImage=findViewById(R.id.xblock);
iname=findViewById(R.id.xname);
xList=new ArrayList<>();
xList.add(new x("engineer",R.drawable.ectangle_32));
xList.add(new x("Artists", R.drawable.ectangle_31));
xList.add(new x("Singers",R.drawable.ectangle_33));
xList.add(new x("Lawyer",R.drawable.ectangle_37));
xList.add(new x("Writters",R.drawable.ectangle_38));
xList.add(new x("developer",R.drawable.ectangle_36));
I1=getIntent();
intent=getIntent();
eName = intent.getStringExtra("eText");
bx = intent.getBooleanExtra("x",false);
if (bx=true) {
String yname = eName.toLowerCase();
for (x yList : xList) {
String xname = yList.getxName().toLowerCase();
if (xname.equals(yname)) {
iname.setText(yList.getxName());
iImage.setImageResource(yList.getxImageId());
}
}
}
boolean x1= intent.getBooleanExtra("t1",false);
if (x1=true){
iImage.setImageResource(R.drawable.ectangle_31);
}
else{x1 = false;}
}
}
But, my app crashes,
It can't get to MainActivity2,
And when check the problem in MainActivity2, it say that my variable is not assigned.
What is the problem here?
Thanks a lot for reading, all this gibberish writing.
Please let me know if i hade made any mistakes.
I think the problem is in getting boolean bx
It shouldbe like this
boolean bx = getIntent().getBooleanExtra(x);
try it if it works

How to dynamically add items to GridView Android Studio (Java)

Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}

How to play a specific sound for a Listview item when it is clicked

I am creating an android dictionary app with sounds... I have listview, when an item is selected, a new activity open, inside the new activity contains 4 textviews and an image button, the textviews function perfectly but the image button was not. The audio files are placed in raw folder. How can I put the specific sounds of an item that was clicked?
Here's the code:
MainActivityJava
public class MainActivity extends AppCompatActivity {
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
MediaPlayer mp;
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
ImageButton playbtn = (ImageButton) findViewById(R.id.playbtn);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
you can pass the raw id in the intent extra and play it on meadiaPlayer
What you want to accomplish is pretty simple.
you can ofcourse pass the id.
But I created this method for your case you can paste it in your activity or class and make a call to it. In my case, I put this method in a class that holds all the common functions, methods, strings, etc. The choice is yours :
public static void playDisSound(Context c, int soundID){
//Play short tune
MediaPlayer mediaPlayer = MediaPlayer.create(c, soundID);
mediaPlayer.setOnCompletionListener( new OnCompletionListener(){
#Override
public void onCompletion( MediaPlayer mp){
mp.release();
}
});
mediaPlayer.start();
}
And this is how to use it in your case :
Example I want to play an audio track from :
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
So I just do :
//TODO ~ pls. remember to define context inside "onCreate" as
//call this before "onCreate"
Context context;
//And do this inside "onCreate" :
context = getApplicationContext();
OR
context = MainActivity.this;
//Then here comes the solution, just make a call to the playDisSound method with the id , in this case the "sounds[postion_referencer_i]"
playDisSound(context, sounds[postion_referencer_i]);
//And now on the question of what your "position_referencer_i" would be .... it also depends on how you intend to pass the id.
Are your going to make a match between the position picked and the position of the sound. It depends on you. But I would have created a set of integers to signify which try I want to play and do a matching simple calculation between the position picked for the item clicked to arrive at the position_referencer_id.
//But simply : note that in your array if I want to play for example "R.raw.baliw" I would just call :
playDisSound(context, R.raw.baliw);
I hope this works perfectly for you. So if I elaborated too much. Do let me know if you may need to stream the sound so I would just paste/send you a very cool method I have been using here in an app am working.
//FINALLY PLS. Remember this : this method would play the sound alright but it wont hesitate to play the sound all over again if you repeat the process. So do remember to check if the sound did play and finished before allowing the user to repeat, if not it could lead to repeated or kind of two speakers playing from the same song but at different time. (And the user may start to think that there is problem with the app. Pls. be very logical and sensitive in using this method)
In solving that, you can disable the button or the UI element that initiates the sound playing until the sound has finished playing, by way of monitoring duration of the track (which I am sure you should know and inculcate into your logic or by simply listening if sound is already playing)
All the best. Era. :)

How to effectively store checkbox values in Custom BaseAdapter

For the past two weeks, I have been struggling to produce a solution to store my checkbox values next to each of my listview items when I exit and open the app. Essentially, I have a custom BaseAdapter class which populates the listview with installed applications on the users phone and a checkbox next to each installed app. When I scroll down the checkbox states stay;however, when I click back or exit and come back it doesn't stay.
I used SharedPreferences in almost every way possible. My last way was using a for loop to create a SharedPreference for each one and restore the boolean in the for loop as well and to store a boolean true and false (for checked and unchecked respectively) in if and else statements.
Here is my code for my BaseAdapter class using SharedPreferences:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.List;
//
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
// http://pastebin.com/Te2g072w, http://pastebin.com/NLT5iUiA ,
SharedPreferences sharedPrefs;
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
String PACKAGE_NAME;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
TextView packageName;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
// Make sure to define it again!
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
Log.d("just loaded??", PACKAGE_NAME);
Log.d("just loaded 2?", appName+position);
// CHANGE UP EVERYTHING! MAKE THIS SHIT WORK, TIGGA!
for(int i= 0; i<packageList.size(); i++){
sharedPrefs = context.getSharedPreferences(String.valueOf(i), Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(String.valueOf(i),false));
}
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(String.valueOf(position), Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
Log.i("This is", " checked: " + position);
editor.putBoolean(String.valueOf(position), true);
Log.d("put true", appName+position);
editor.apply();
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
Log.i("This is", " not checked: " + position);
editor.putBoolean(String.valueOf(position), false);
Log.d("put false", appName+position);
editor.apply();
}
}
});
return convertView;
}
}
I have also created a DatabaseHandler class and Object class for using SQLite database to store my checkbox values instead after unsuccessfully storing it with SharedPreferences.
Here are the pastebin links so I don't clog the post:
DatabaseHandler class: http://pastebin.com/NzKhBiZ3
Object class: http://pastebin.com/Jp3BLXba
I know that there are many posts, blogs, and links on using custom adapters/listviews and saving checkboxes and button states etc using SQLite and SharedPreferences, but I assure you I have done my fair share of research for weeks, but I haven't been able to find something that works for my specific case.
Some examples:
Saving State of the checkbox in a custom list view with Checkboxes
http://blog.csdn.net/qu213/article/details/9289349
What would be the most optimal option in my particular case and How would I produce a solution in my situation to successfully save the checkbox states next to each installed app listview item that would be saved after I exit the application and re-enter? Some code would really be of help.
Thank you for your time.
Let me know if you need me to include any xml files.
I think I may have solved your problem. Please try thise code and see if it works.
for(int i= 0; i<packageList.size(); i++){
PACKAGE_NAME = packageInfo.packageName;
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
Log.d("just got sharedpref??", PACKAGE_NAME);
holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));
Log.d("just got boolean??", PACKAGE_NAME);
}
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(packageInfo.packageName, Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
Log.i("This is", " checked: " + position);
editor.putBoolean(packageInfo.packageName, true);
Log.d("put true", packageInfo.packageName);
editor.apply();
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
Log.i("This is", " not checked: " + position);
editor.putBoolean(packageInfo.packageName, false);
Log.d("put false", packageInfo.packageName);
editor.apply();
}
}
});
I passed in the packagenames for the keys. :)
what i would suggest in your case is to define an object that would deal with storing and retrieving state data. Lets say you have an AppHandler class as your main object and AppState class
for keeping state related data such as your checkboxes.
public class AppHandler {
private List<AppState> lastInstalledApp;
#transient
private Gson gson;
public void retrieve(SharedPreferences pref){
// parse the gson from shared preferences
// create the lastInstalledApp list
String jsonState = pref.getString("APP_STATE", null);
if(jsonState != null)
lastInstalledApp = gson.fromJson(jsonState, lastInstalledApp.getClass());
}
public void store(SharedPreferences pref){
// store the data to shared preferences
}
public List<AppState> getAppList(){
return lastInstalledApp;
}
public static class AppState{
protected boolean lastCheckbox;
protected String name;
public boolean isLastCheckbox() {
return lastCheckbox;
}
public void setLastCheckbox(boolean lastCheckbox) {
this.lastCheckbox = lastCheckbox;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Use shared preferences to store the entire AppHandler object as a JSON string (use GSON for this) so you access the storage file only once and not every time you want to access a single checkbox state. You can retrieve and store this data on your activity (the adapter initiate it with your appHandler.getAppList() data):
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.list_layout);
appHandler = new AppHandler();
appHandler.retrieve(getSharedPreferences());
}
#Override
protected void onDestroy() {
appHandler.store(getSharedPreferences());
super.onDestroy();
}
within the your custom adapter access the specific application by their package names in order to get the state of checkbox. you may even extend ArrayList and add some methods like getAppByName() so you can keep a clear distinction between objects.
when changing the checkbox state update the equivalent boolean value of the AppState object. This is in general terms.
Use sqlite database ...Everytime the user checks/unchecks the value make an entry in the database.
App1 checked
App2 checked
App3 checked
App4 unchecked

Linking ListView objects to layouts android

Ive searched for this all over the internet and there seems to be no simple explanation or tutorial on how to do this.
Basically, I want a layout that has a ListView where the user can click on an object and it will take them to the next layout.
In other words, using the listview as links to other layouts.
Everything Ive found on the internet has the end result of using a Toast... However I dont want a toast, i want to link to the next page.
Your question is slightly confusing so I'm going to make an assumption.
Is [LinearLayout1 LinearLayout2 Breadcrumb] suppose to be navigation or tabs that when selected insert their corresponding content into the Main Content?
If so I would suggest using fragments for each piece of content. Then when you click the navigation/tab, perform an animation of the fragment which slides the content in and out.
See the google docs for how to use fragments: http://developer.android.com/guide/components/fragments.html
See another stackoverflow answer for how to do the slide animation: Android Fragments and animation
or
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
Here is some code that outlines how to invoke an activity following a click on a list row. Hopefully you can adapt the Toast example you mention to make this work for you.
The basic idea is that you launch a new Activity with a new Intent. You can pass any data you need from the listView row as an extra in the Intent.
final static String[] months = new String[] {"Jan","Feb","Mar"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row_layout, R.id.text1, months);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
int intItem = (int)id;
Intent intent= new Intent(this, SecondaryActivity.class);
intent.putExtra("MONTH", intItem);
startActivity(intent);
}
Why using ListView for it?
Each row must lead to different layout?
Its main benefits is in displaying dynamically changing data, but in your case data is constant, right?
Use vertical LinearLayout, fill it programmatically with "list elements", and add
leListComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(YourActivity.this, TargetActivity.class));
}
});
to each.
If i didn't get it, and you feel good of using some adapter, it can be like this:
public class LeWrapper {
private String caption;
private Class<? extends Activity> target;
...POJO here...
}
v.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//get leWrapper object from adapter
startActivity(new Intent(MenuActivity.this, leWrapper.getTarget()));
}
});
but its kinda overkill
Thanks for all the help guys. Sorry ive took my time replying. My solution is below :)
public class FP_WL1_ListView extends Activity {
private ListView lv1;
private String lv_arr[]={"Exercise Bike", "Treadmill", "Cross Trainer", "Squats", "Lunges"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fitnessprograms_wlday_one);
lv1=(ListView)findViewById(R.id.list);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final TextView mTextView = (TextView)view;
switch (position) {
case 0:
Intent newActivity0 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_sp.class);
startActivity(newActivity0);
break;
case 1:
Intent newActivity1 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Treadmill.class);
startActivity(newActivity1);
break;
case 2:
Intent newActivity2 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Crosstrainer.class);
startActivity(newActivity2);
break;
case 3:
Intent newActivity3 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Squats.class);
startActivity(newActivity3);
break;
case 4:
Intent newActivity4 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Lunges.class);
startActivity(newActivity4);
break;
}
}
});
} }

Categories

Resources