I have a listview in my app, if I click one item from the list, it gets highlighted. Then if I click another item, that highlight shifts to that item. But if the scroll the list after selecting an item and then select another item from another part of the list, both of them remains highlighted. But not if I don't scroll the screen. What is causing this? And how to deal with it?
ListAdapter.java
package com.example.mp3;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter{
private Context _context;
private List<String> list;
public ListAdapter(Context _context,List<String> list)
{
this._context=_context;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
View row = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
}
TextView textView = (TextView) row.findViewById(R.id.rowTextView);
textView.setText(list.get(position).toString());
return row;
}
}
MainActivity.java
package com.example.mp3;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> adapter ;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title;
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MainActivity.class.getSimpleName();
private Context _context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
//list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
_context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
EditText editText = new EditText(getApplicationContext());
getActionBar().setCustomView(editText);
//bar.setDisplayShowTitleEnabled(true);
//bar.setDisplayHomeAsUpEnabled(true);
Scanner("/sdcard/");///storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
//listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
ListAdapter listAdapter=new ListAdapter(_context,listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
///////////////////changing list item background on click///////////////////
list.clearChoices();
//list.setSelection(position);
view.setSelected(true); ///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
String selected = listTest.get(position);
list.setItemChecked(position, true);//
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
}
else
{
index = (list.getAdapter().getCount()-1)-1;
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
play.setImageResource(R.drawable.play);
}
/*#Override
protected void onStop() {
super.onStop();
mp.stop();
Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
}*/
//////////////////////////////////////////Search box/////////////////////////////////////////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
//Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
try
{
File fl = new File("/sdcard/");
File[] listOfFiles = fl.listFiles();
String selectedPath="";
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
{
selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM
//listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();
/*mp.setDataSource(selectedPath);
mp.prepare();
mp.start();*/
}
/////////////////////////////////
File f = new File("/sdcard/"+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner("/sdcard/"+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
The cause of this problem is the way Android recycles the ListView items. A way to prevent something like this is to manually save wich item is clicked. In your adapter you can make a variable wich holds the current selected item. In your getView you will have to check if the current item is the same as selected. It will look something like this:
if(row==currentSelected){
//set background color
else{
//another background color -> this is important otherwise all listview items will have the same background color after swiping up and down
}
Hello, try with this.
1- Your activity extend from ListActivity. 2-Create the next adapater
for your list, you can create this adapter inside your activity:
private class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return items.length;
}
#Override
public String getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return items[position].hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item,
container, false);
}
((TextView) convertView.findViewById(android.R.id.text1))
.setText(getItem(position));
ImageView imageView = (ImageView) a convertView.findViewById(R.id.imageView_Icon);
imageView.setImageResource(imagesId[position]);
return convertView;
}
}
items = Array String with the text items. imagesId = Array with the
image's id in your draweable.
In the layout create the next list_item.xml
<com.Test.CheckableLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:minHeight="?android:listPreferredItemHeight"
android:gravity="center_vertical">
<ImageView
android:id="#+id/imageView_Icon"
android:layout_height="60dp"
android:contentDescription="IconDescription"
android:layout_width="60dp" />
<TextView android:id="#android:id/text1"
android:duplicateParentState="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#color/hideable_text_color" />
<ImageView android:src="#drawable/ic_hideable_item"
android:duplicateParentState="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:id="#+id/imageView1" />
</com.Test.CheckableLinearLayout>
In your Activity set adapter in the ListView:
ListView listTest = (ListView) findViewById(R.id.listTest);
listTest .setAdapter(new MyAdapter());
If you need a best example, go to Import Sample -> Select your version
y go to List, here is excelente example for the list multi select.
Related
I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!
A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}
you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode
In my Android app, I am trying to place a ListView in my FragmentActivity. Unfortunately there is no such thing as FragmentListActivity. The problem is that I can't call setListAdapter() and onListItemClick() methods.
So I did a lot of research and I went to my XML file and manually added the ListView there. Then instead of getListView(), I declared a ListView variable so I could call the methods on my new ListView variable. Unfortunately the method is still riddled with errors The method is unable to be resolved etc.
Here is my java code:
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
//Implementing the Listview Programatically
ListView InstalledAppList = (ListView) findViewById(R.id.Installed_List);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
//here
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InstalledAppActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is my XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Installed_List"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this..
You have missed onCreate
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
and remove onCreateView and add ItemClickListener also inside onCreate
public class MyAndroidVersionListFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
CustomDoctorsListAdapter adapter= new CustomDoctorsListAdapter(getActivity(), getResources().getStringArray(R.array.doctors_name), getResources().getStringArray(R.array.doctors_address),
getResources().getStringArray(R.array.doctors_category), getResources().obtainTypedArray(R.array.doctors_rating), getResources().getIntArray(R.array.doctors_clinic_distance));
getResources().obtainTypedArray(R.array.doctors_rating).recycle();
android.R.layout.simple_list_item_multiple_choice, android_versions);
setListAdapter(adapter);
Toast.makeText(getActivity(), "Mypostion"+position+"", Toast.LENGTH_LONG).show();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
position = getArguments().getInt("second");
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
try List fragment like this hope it will help you
A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|"|&|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.
I am making an android application where i got a seekbar for some music. I got the seekbar to show the music playing status, where i currently am in the music playback. But how can i setup a listener so that i can say that the mediaplayer would play a specific place on a track? I know the code for setting the play time in mediaplayer, but how can i handle the click events from seekbar? like onClick() or anything similar?
FIXED:
My code:
package com.mycompany.appname;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
public class MusicActivity extends ListActivity implements OnClickListener, OnSeekBarChangeListener {
//Called when the activity is first created
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
static final String[] COUNTRIES = new String[] {
"Movies"
};
MediaPlayer mp1;
String musicUri;
Button PausePlay;
int positionInt;
SlidingDrawer slidingDrawer2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musicscreen);
//Import views
PausePlay = (Button)findViewById(R.id.PausePlay);
slidingDrawer2 = (SlidingDrawer)findViewById(R.id.slidingDrawer2);
//Setup onClickListener for the buttons
PausePlay.setOnClickListener(this);
//Setup mediaPlayer
mp1 = new MediaPlayer();
//Setup ListView
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setOnSeekBarChangeListener(this);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
File mFile = new File(Environment.getExternalStorageDirectory() + "/Music/");
myList.addAll(Arrays.asList(mFile.list()));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//When an item is clicked, play it on a MediaPlayer
//Play song
positionInt = position;
if (mp1.isPlaying()) {
//Reset mediaPlayer
mp1.reset();
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(positionInt);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(position);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setProgress(0);
progress.setMax(mp1.getDuration());
new CountDownTimer(mp1.getDuration(), 250) {
public void onTick(long millisUntilFinished) {
if (progress.getProgress() == mp1.getDuration()) {
mp1.reset();
progress.setProgress(0);
} else {
progress.setProgress(mp1.getCurrentPosition());
}
}
public void onFinish() {}
}.start();
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser == true) {
mp1.seekTo(seekBar.getProgress());
} else {
//Do nothing
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK)) {
if (mp1.isPlaying()) {
mp1.reset();
System.exit(0);
} else {
finish();
}
return true;
}
return super.onKeyDown(KeyCode, event);
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.PausePlay:
if (mp1.isPlaying()) {
mp1.pause();
PausePlay.setText("Play");
} else {
mp1.start();
PausePlay.setText("Pause");
}
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
My xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Musikk"
android:textAppearance="?android:attr/textAppearanceLarge" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<SlidingDrawer
android:id="#+id/slidingDrawer2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="#+id/content"
android:handle="#+id/handle" >
<Button
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spiller nå" />
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SeekBar
android:id="#+id/musicProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/PausePlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
</LinearLayout>
You'll want to implement SeekBar.OnSeekBarChangeListener, then implement the onProgressChanged method.
This is called when the progress is changed (eg a user click somewhere on the seekbar), and will provide you with the new position.
Example:
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {
// Do something
}
Don't forget to register the OnSeekBarChanged listener with seekBar.setOnseekBarChangeListener
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp1.seekTo(progress);
seekBar.setProgress(progress);
}
}
i have 2 arrays first for Hours and second for minutes, this is my arrays declare it in string.xml
` <string-array name="feedbacktypelist">
<item>#string/hr0</item>
<item>#string/hr1</item>
<item>#string/hr2</item>
</string-array>
<string-array name="array2">
<item>#string/min5</item>
<item>#string/min10</item>
<item>#string/min15</item>
<item>#string/min20</item>
<item>#string/min25</item>
<item>#string/min30</item>
<item>#string/min35</item>
<item>#string/min40</item>
<item>#string/min45</item>
<item>#string/min50</item>
<item>#string/min55</item>
<item>#string/min59</item>
</string-array>`
and this is my code in java
package lmp.app.pkg;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class CreateNewForm extends Activity implements OnItemSelectedListener {
Button Browse;
ImageView CasePic;
Spinner CaseDurationH, CaseDurationM;
TextView tesst;
RadioGroup GenderSelection;
EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
Button Next;
//For Browsering Picture
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_form);
//To Call initializer Function
initializer();
//j list
// 1-For Uploading Picture
Browse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
// 1-Name
final MyCase case1 = new MyCase();
case1.setName(CaseName.getText().toString());
// 2-Gender For Group Radio
GenderSelection.clearCheck();
GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio0:
case1.setGender("Male");
break;
case R.id.radio1:
case1.setGender("Female");
break;
default:
break;
}
}
});
//3-Age
String age = CaseAge.getText().toString();
/*int tstnum =case1.getAge();
tesst.setText(tstnum); */
//4-Duration Time
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CaseDurationH.setAdapter(adapter);
//5-Case Clothes
case1.setClothes(CaseClothes.getText().toString());
//6-Case More Information
case1.setMoreInfo(CaseMoreInfo.getText().toString());
//Move to 2nd form page
Next= (Button)findViewById(R.id.Next2);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.Next2:
try
{
Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);
startActivity(k);
}catch(Exception e){
}
break;
}
}
});
//Spinner
CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
int i =CaseDurationH.getSelectedItemPosition();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int i = CaseDurationH.getSelectedItemPosition();
if(i==2){
CaseDurationM.setEnabled(false);
}
String str = parent.getSelectedItem().toString();
if(str.equals("hr0"))
{
}
if(str.equals("hr1"))
{
}
if(str.equals("hr2"))
{
CaseDurationM.setEnabled(false);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
// To initialize the variables
private void initializer() {
// TODO Auto-generated method stub
//This information will be filled by a user
//CasePic = (ImageView) findViewById(R.id.imageView1);
CaseName= (EditText) findViewById(R.id.caseNm);
GenderSelection= (RadioGroup) findViewById(R.id.radioGroup1);
CaseAge= (EditText) findViewById(R.id.caseaage);
tesst= (TextView) findViewById(R.id.textView8);
CaseDurationH= (Spinner) findViewById(R.id.Shr);
CaseDurationM= (Spinner) findViewById(R.id.Smin);
CaseClothes= (EditText) findViewById(R.id.caseClothes);
CaseMoreInfo= (EditText) findViewById(R.id.caseMrInfo);
CasePic = (ImageView) findViewById(R.id.casepic);
Browse = (Button) findViewById(R.id.browseCasePic);
}
//For Uploading Picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
//For Uploading Picture
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
i want:
1- retrieve the item in spinner that the user choose it, not the positon
2-if the user choose from spinner1 the item "hr02" then the spinner2 will disable
Thank you for help me, StackOverFlow members your my hero now! :")
use this
String str = parent.getSelectedItem().toString();
if(str.equals("hr2")
{
spinner2.setEnabled(false);
}
Try this:
String str = parent.getSelectedItem().toString();
if (str.equals("hr0")){
//retrieve the item as string
}
if (str.equals("hr1")){
//retrieve the item as string
}
if (str.equals("hr2")){
//retrieve the item as string
//make the 2nd spinner disable
}