Can't show Spinner DropDown list inside AlertDialog - Android - android

I have two spinners in an AlertDialog, the spinners look good, and the list of items is correct, it shows the first items of each list. But when I click any of the two spinner, the dropdown list is not displayed to select some other item. The spinners do nothing. This does not happen when I was the same two spinners outside the AlertDialog.
This is the code of AlertDialog:
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.layout_spinners,null);
sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
//configuracion de textos en memoria sd
String path = Environment.getExternalStorageDirectory().toString()+"/Textos/";
File f = new File(path);
String[] fileStr = f.list();
ArrayList<String> lista_lista_CARPETAS = new ArrayList<String>();
for (String lista_texto : fileStr) {
lista_lista_CARPETAS.add(lista_texto);
}
Collections.sort(lista_lista_CARPETAS, new AlphanumComparator());
String[] lista_k = f.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return f.isDirectory();
}
});
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = f.listFiles(fileFilter);
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
//ARRAY CON TITULOS DE ARCHIVOS TXT
String camino = Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos"+ "/";
File t = new File(camino);
String[] lista_textos = t.list();
ArrayList<String> lista_lista_textos = new ArrayList<String>();
for (String lista_texto : lista_textos) {
if (lista_texto.toLowerCase().endsWith(".txt")) {
lista_lista_textos.add(lista_texto);
}
}
for (int index =0; index < lista_lista_textos.size(); index++){
lista_lista_textos.set(index, WordUtils.capitalizeFully(lista_textos[index].toLowerCase().replace(".txt", "")));
}
Collections.sort(lista_lista_textos, new AlphanumComparator());
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String nombre_texto = parent.getSelectedItem().toString();
File sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos/");
//Get the text file
File file = new File(sdcard, nombre_texto);
//Read text from file
StringBuilder text = new StringBuilder();
int BUFFER_SIZE = 8192;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1252"),BUFFER_SIZE);
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String nuevoTexto = text.toString().replaceAll("\t", " ");
String nuevoTextoA = nuevoTexto.replaceAll("\n", " ");
Holmes1 = nuevoTextoA;
delimitadores = " ";
tokenHolmes1 = new StringTokenizer(Holmes1, " ");
arrayHolmes1 = Holmes1.split(delimitadores);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
And the xml for the spinners:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="100"
style="#style/spinner_rojo">
<Spinner
android:id="#+id/spinner_titulo_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
<Spinner
android:id="#+id/spinner_textos_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
</LinearLayout>
And an image:
Anyone know any possible sulucion to show the drop down list?

I just copied your code and edit ArrayList. It totally worked for me.
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.spinner_layout,null);
Spinner sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
Spinner sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
ArrayList<String> lista_k = new ArrayList<String>();
lista_k.add("Path A");
lista_k.add("Path B");
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
ArrayList<String> lista_lista_textos = new ArrayList<String>();
lista_lista_textos.add("Path C");
lista_lista_textos.add("Path D");
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}

Move this to the end of the code, so you are doing it after setting everything up:
builder.show();

Create custom alert dialog for same. Try this
Dialog new_dialog = new Dialog(getParent());
// new_dialog.setTitle("Book your appointment");
new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
new_dialog.setContentView(R.layout.customize_dialog_list_view);
new_dialog.setCancelable(false);
cuc = new CommanUtilityClass();
SharedPreferences sp = getSharedPreferences("provider",0);
String services = sp.getString("services", "");
TextView service = (TextView) new_dialog
.findViewById(R.id.cdlv_service_provider);
TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
//String[] ampm = myTiming[which].split(":");
/*String[] range = myTiming[which].split(":");
int startTimeInt = Integer.parseInt(range[0])
* 60 + Integer.parseInt(range[1]);
String finalvalue = "";
if(startTimeInt >= 720){
if(startTimeInt >= 780){
}else{
}
}else{
finalvalue = String.valueOf(range[0] + ":" + range[1] + " AM");
}
for (int i = 0; i < range.length; i++) {
String startTimeString = range[i].split("-")[0];
String endTimeString = range[i].split("-")[1];
Log.d("Minutes", "startTimeString = " + startTimeString);
Log.d("Minutes", "endTimeString = " + endTimeString);
int startTimeInt = Integer.parseInt(startTimeString.split(":")[0])
* 60 + Integer.parseInt(startTimeString.split(":")[1]);
int endTimeInt = Integer.parseInt(endTimeString.split(":")[0]) * 60
+ Integer.parseInt(endTimeString.split(":")[1]);
}*/
appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
service.setText(Html
.fromHtml("<b>Service provider :</b>"
+ cuc.toTheUpperCase(bsp_name)));
hour.setText(Html
.fromHtml("<b>Working hours :</b>"
+ cuc.toTheUpperCase(bsp_availability)));
try {
lv = (ListView) new_dialog
.findViewById(R.id.cdlv_list);
CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(
getApplicationContext(),
m_ArrayList);
lv.setAdapter(cdaa);
} catch (Exception e) {
e.printStackTrace();
}
new_dialog.show();
Here I have just inflated xml layout to alert dialog. Make sure you fetch each spinner with context to dialog. See above code for same.
Hope it helps. Cheers!

Due to memory leak, happening so, When you are opening the one spinner it is able to get the valid context, but second time when you are trying to retrieve the another spinner it's actually getting null as a context and not populating anything. But When you are using both the spinner in Activity out of Alert-Dialog, its' actually getting a valid context always. Thus for that time you are not getting any error and it populates correctly.
So, to avoid memory leak, use getApplicationContext() to retrieve the context for spinner ArrayAdapter
ArrayAdapter<String> carpetas = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_k);
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_lista_textos);

Related

Adding TextView dynamically under the relativeLayout

enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}

how to update listview in Popup window in Android

I have one TextView with title All Post.I'm displaying the popup window click on TextView and populate list view with two items in popup window.And trying to implement this - whenever click on list view item that item will be display in TextView and previous TextView title All Post will be add in listview in the place of clickable item.But my listview is not update on dismiss the popup window.
Here is my code of popup window.
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++) {
String str_PostType = arr.get(i);
if (!str_PostType.equals(str_LastSelectionValue)) {
filter_PostType.add(str_PostType);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
removeItemFromList(position);
filterPost_adapter.notifyDataSetChanged();
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++)
{
String str_PostType = arr.get(i);
if (!str_PostType.equals(textSearch.getText().toString().trim()))
{
filter_PostType.add(str_PostType);
int filterSize = filter_PostType.size();
Log.e(" UnMatched ", " In ListItem Click filterSize = " + filterSize);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
}
});
}
});
Use something like this:
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "NoVal");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
if(!filter_PostType.isEmpty())
filter_PostType.clear();
for (int i = 0; i < values.length; i++) {
if (!values[i].equals(str_LastSelectionValue)) {
filter_PostType.add(values[i]);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
str_LastSelectionValue=selectedFromList;
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
}
});
}
});
}
You don't need to change your adapter after user selects something because the next time user clicks the textview, you are making a new popup window with a new adapter.
If there is anything you don't understand, leave a comment.
Hope this helps :)

Getting auto complete list from txt file for MultiAutoCompleteTextView (re-posted)

Someone marked this question as duplicate(What is a NullPointerException, and how do I fix it?), but that didn't help at all.
I'm reposting the question.
//
I'm just learning myself and pretty new to android programming and java.
I'm trying to get list from a txt file which is located in internal storage.
This is what I have done.
try {
path = getFilesDir().getAbsolutePath() ;
FileInputStream inFs = new FileInputStream(new File(path.toString() + "/filesitem_" + Type + ".txt"));
byte[] txt = new byte[inFs.available()];
while (inFs.read(txt) != -1) {}
String[] list_item = new String(txt).split(",");
item_actv = (MultiAutoCompleteTextView) dlgView.findViewById(R.id.Item_AutoTxtView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list_item);
MultiAutoCompleteTextView.CommaTokenizer token = new MultiAutoCompleteTextView.CommaTokenizer();
item_actv.setTokenizer(token);
item_actv.setAdapter(adapter);
} catch (IOException e) {
Toast.makeText(Activity_list.this, "No item list.", Toast.LENGTH_SHORT).show();
}
itemQuant_np = (NumberPicker) dlgView.findViewById(R.id.ItemQuant_Np);
itemQuant_np.setMinValue(1);
itemQuant_np.setMaxValue(10);
SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd", Locale.KOREA);
Date current = new Date();
date = formater.format(current);
AlertDialog.Builder dlg2 = new AlertDialog.Builder(Activity_list.this)
.setTitle("New List")
.setView(dlgView)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
path = getFilesDir().getAbsolutePath() + "/" + Type + "_list";
FileOutputStream outFs = new FileOutputStream(new File(path + "/" + date + " list_" + Type + ".txt"), true);
listContent = item_actv.getText().toString() + "\t\t\t" + Integer.toString(itemQuant_np.getValue()) + "\n";
outFs.write(listContent.getBytes());
outFs.close();
Toast.makeText(Activity_list.this, "Saved.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(Activity_list.this, "The file is already exist.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", null);
dlg2.show();
This dialog shows up when I click a item on a menu.
What it supposed to do is that the diglog would show up, and as I enter a name of item into MultiAutoCompleteTextView, it will show me available list which is from a txt file already saved in internal storage. In the txt file, there are list of items separated by comma(ex: apple,grape,orange). If I hit the Confirm button on the dialog after I fill MultiAutoCompleteTextView and set quantity of the item, it will create a new txt file into designated path.
The diglog shows up correctly, but the issues are
the app stops when I hit "Confirm" button on the dialog (Unfortunately, the app has stopped)
(java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.MultiAutoCompleteTextView.getText()' on a null object reference)
seems like it is not getting auto completion list for MultiAutoCompleteTextView
it creates new txt file, but the content is empty
I really need your help :(
+Activity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Manage snacks");
setContentView(R.layout.subactivity);
Intent intent = getIntent();
Type = intent.getStringExtra("Type");
fileList = (ListView) findViewById(R.id.FileList);
arFiles = new ArrayList<>();
File file = new File(getFilesDir().getAbsolutePath() + "/" + Type + "_list");
arFiles.addAll(Arrays.asList(file.list()));
flAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arFiles);
fileList.setAdapter(flAdapter);
fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = arFiles.get(i);
Intent intent = new Intent(Activity_list.this, Activity_listspec.class);
intent.putExtra("Type", Type);
intent.putExtra("fileName", name);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, 1, 0, "Add new item");
menu.add(0, 2, 0, "Add new list");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
dlgView = View.inflate(Activity_list.this, R.layout.dlg_newitem, null);
edtTxtNewItem = (EditText) dlgView.findViewById(R.id.EdtTxtNewItem);
AlertDialog.Builder dlg1 = new AlertDialog.Builder(Activity_list.this)
.setTitle("New item")
.setView(dlgView)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
path = getFilesDir().getAbsolutePath();
FileOutputStream outFs = new FileOutputStream(new File(path + "item_" + Type + ".txt"), true);
itemList = edtTxtNewItem.getText().toString() + ",";
outFs.write(itemList.getBytes());
outFs.close();
Toast.makeText(getApplicationContext(), edtTxtNewItem.getText().toString() + " Item added.", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Cancel", null);
dlg1.show();
return true;
case 2:
dlgView = View.inflate(Activity_list.this, R.layout.dlg_newlist, null);
try {
path = getFilesDir().getAbsolutePath() ;
FileInputStream inFs = new FileInputStream(new File(path.toString() + "/filesitem_" + Type + ".txt"));
byte[] txt = new byte[inFs.available()];
while (inFs.read(txt) != -1) {}
String[] list_item = new String(txt).split(",");
item_actv = (MultiAutoCompleteTextView) dlgView.findViewById(R.id.Item_AutoTxtView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list_item);
MultiAutoCompleteTextView.CommaTokenizer token = new MultiAutoCompleteTextView.CommaTokenizer();
item_actv.setTokenizer(token);
item_actv.setAdapter(adapter);
} catch (IOException e) {
Toast.makeText(Activity_list.this, "No existing list.", Toast.LENGTH_SHORT).show();
}
itemQuant_np = (NumberPicker) dlgView.findViewById(R.id.ItemQuant_Np);
itemQuant_np.setMinValue(1);
itemQuant_np.setMaxValue(10);
SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd", Locale.KOREA);
Date current = new Date();
date = formater.format(current);
AlertDialog.Builder dlg2 = new AlertDialog.Builder(Activity_list.this)
.setTitle("New List")
.setView(dlgView)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
path = getFilesDir().getAbsolutePath() + "/" + Type + "_list";
FileOutputStream outFs = new FileOutputStream(new File(path + "/" + date + " list_" + Type + ".txt"), true);
listContent = item_actv.getText().toString() + "\t\t\t" + Integer.toString(itemQuant_np.getValue()) + "\n";
outFs.write(listContent.getBytes());
outFs.close();
Toast.makeText(Activity_list.this, "Saved.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(Activity_list.this, "The file is already exist.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", null);
dlg2.show();
return true;
}
return false;
}
}
subactivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/FileList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
dlg_newitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<EditText
android:id="#+id/EdtTxtNewItem"
android:hint="상품명"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"/>
</LinearLayout>
dlg_newlist.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<MultiAutoCompleteTextView
android:id="#+id/Item_AutoTxtView"
android:hint="상품명"
android:completionThreshold="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"/>
<NumberPicker
android:id="#+id/ItemQuant_Np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp">
</NumberPicker>
</LinearLayout>
try this
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dlg_newitem, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("New item");
EditText edtTxtNewItem= (EditText) dialogView.findViewById(R.id.EdtTxtNewItem);
editText.setText("");
dialogBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
try {
path = getFilesDir().getAbsolutePath();
FileOutputStream outFs = new FileOutputStream(new File(path + "item_" + Type + ".txt"), true);
itemList = edtTxtNewItem.getText().toString() + ",";
outFs.write(itemList.getBytes());
outFs.close();
Toast.makeText(getApplicationContext(), edtTxtNewItem.getText().toString() + " Item added.", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
dialogBuilder.setNegativeButton("Cancel", null);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Trying to set the marker on the current position gives me nullpointer exception

I have done the following things in my program:
I am generating some Buttons programmatically in my MenuItemsActivity class. I have a Listview in the xml of the MenuItemsActivity class.
When I click on the button the appropriate contents get loaded in the Listview. I just refresh the activity i.e I am using the same Listview to load different contents based on the button which is clicked.
I want to do the following:
When the Button is clicked I want to change the background of the button to 'blue_tab` and maintain that same color when the same activity reloads. Can anyone guide me step by step what to do, as I am a newbie to Android.
i = getIntent();
String Salad=i.getStringExtra("Salad");
String cat_name_from_fragment=i.getStringExtra("category name");
final ListView salad_list = (ListView) findViewById(R.id.salads);
category = new ArrayList<HashMap<String, String>>();
items = new ArrayList<HashMap<String, String>>();
db = new DbHelper(MenuItemsActivity.this);
category.clear();
if (i.getStringExtra("category name") != null) {
String getcategory = i.getStringExtra("category name").toString();
items = db.retrieve_item_details(getcategory);
Log.i("sub items", "" + items);
}
else if(cat_name_from_fragment!=null)
{
items = db.retrieve_item_details(cat_name_from_fragment);
}
else
{
items = db.retrieve_item_details("Salads");
}
category = db.retrieve_category_name();
count = category.size();
Log.i("Sqlite database values", "" + count + " " + category);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
LinearLayout l1 = (LinearLayout) findViewById(R.id.tableRow1);
int i = 0;
for (HashMap<String, String> map : category)
for (Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LinearLayout.LayoutParams(40, 90));
Log.i("map", "" + value);
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
});
/*TextView tv2 = new TextView(this);
tv2.setText(" ");
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);*/
l1.addView(tv1);
l1.addView(tv2);
i++;
Log.e("i count ", "" + i);
}
final int imageArra[] = { R.drawable.leftbar_logo ,R.drawable.leftbar_logo};
ListAdapter k = new SimpleAdapter(MenuItemsActivity.this, items,
R.layout.menulist, new String[] { "Item_Name", "Desc",
"Currency", "Price","url","veggie","cat" }, new int[] { R.id.cat_name,
R.id.textView1, R.id.textView2, R.id.textView3,R.id.url,R.id.veggie,R.id.Category}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v = super.getView(position, convertView, parent);
final ImageView im=(ImageView)v.findViewById(R.id.imageView1);
TextView url=(TextView)v.findViewById(R.id.url);
TextView veg=(TextView)v.findViewById(R.id.veggie);
String vegg=veg.getText().toString();
ImageView imagevegs=(ImageView)v.findViewById(R.id.veggies);
Log.i("veggie",""+vegg);
if(vegg.compareToIgnoreCase("Veg")==0)
{
imagevegs.setImageResource(R.drawable.veg);
imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
else
{imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imagevegs.setImageResource(R.drawable.non);
}
final String urls="http://166.62.17.208/"+url.getText().toString();
Log.i("urls",""+urls);
imageLoader.DisplayImage(urls,im);
//return super.getView(position, convertView, parent);
return v;
}
};
salad_list.setAdapter(k);
You can use PreferenceManager to save data and use it when the app is reloaded/restarted
sample:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
if(PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).getString("button", "").length != 0)
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
else
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).edit();
editor.putString("button", "1");
editor.commit();
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
}
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}

Correct item is not selected in Listview

I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.
This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????
Class Blog.java
public class Blog extends Activity {
ListView listView;
ArrayList< String>arrayList; // list of the strings that should appear in ListView
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
listView = (ListView) findViewById(R.id.lstDemo);
// LIST OF STRINGS / DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED IT WE CAN TAKE THIS INPUT FROM USER AS WELL
arrayList = new ArrayList();
arrayList.add("India");
arrayList.add("USA");
arrayList.add("England");
arrayList.add("Singapur");
arrayList.add("China");
arrayList.add("Canada");
arrayList.add("Srilanka");
arrayList.add("SouthAfrica");
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList);
listView.setAdapter(arrayAdapter);
// LETS HIGHLIGHT SELECTED ITEMS
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long itemId) {
/*
* when we click on item on list view we can get it catch item here.
* so view is the item clicked in list view and position is the position
* of that item in list view which was clicked.
*
* Now that we know which item is click we can easily change the color
* of text but when we click on next item we we have to deselect the old
* selected item means recolor it back to default , and then hight the
* new selected item by coloring it .
*
* So here's the code of doing it.
*
*
* */
CheckedTextView textView = (CheckedTextView) view;
for (int i = 0; i < listView.getCount(); i++) {
textView= (CheckedTextView) listView.getChildAt(i);
if (textView != null) {
textView.setTextColor(Color.WHITE);
}
}
listView.invalidate();
textView = (CheckedTextView) view;
if (textView != null) {
textView.setTextColor(Color.BLUE);
}
}
});
}
}
My xml View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Define your variables like this
private ProgressDialog pDialog;
private ListView lv;
private ArrayList<GoModelAll> m_ArrayList = null;
GoArrayAdapter gaa;
Define your AsyncTask like this
new GoAsyncTask().execute();
Your AsyncTask class Code like this
class GoAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
pd.show();
}
#Override
protected String doInBackground(String... params) {
sal = new StaticApiList();
myUrl = StaticApiList.go_api;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
Log.i("talk_all_json", jsonString);
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
return null;
}
#SuppressWarnings("static-access")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
vivek = true;
try{
m_ArrayList = new ArrayList<GoModelAll>();
if (jsonString.length() > 0) {
JSONArray jArray = new JSONArray(jsonString);
dh.open();
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
description = jObject.getString("description");
excert = jObject.getString("excert");
thumsrc = jObject.getString("thumsrc");
title = jObject.getString("title");
postid = jObject.getInt("postid");
Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc
+ " , excert -> " + excert + " , description -> " + description);
Log.d("talklog", "============================= end of " + i + " ===============================");
gma = new GoModelAll();
gma.description = description;
gma.excert = excert;
gma.thumsrc = thumsrc;
gma.title = title;
gma.postid = postid;
Cursor cursor = dh.getSeenStatus(gma.postid);
if(cursor.getCount()>0)
{
cursor.moveToFirst();
if(cursor.getInt(0) == 0)
{
gma.isSeen = false;
}
else
{
gma.isSeen = true;
}
}
else
{
ContentValues cv = new ContentValues();
cv.put(DbHandler.KEY_ID, postid);
cv.put(DbHandler.KEY_VALUE, 0);
dh.addData(DbHandler.TABLE_SEEN, cv);
}
m_ArrayList.add(gma);
}
dh.close();
}
gaa = new GoArrayAdapter(getActivity(), m_ArrayList);
lv = (ListView) getActivity().findViewById(R.id.go_list);
lv.setVisibility(View.VISIBLE);
lv.setAdapter(gaa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
dh.open();
dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1);
m_ArrayList.get(arg2).isSeen = true;
dh.close();
GoDetail fragment = new GoDetail();
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc);
bundle.putString("header_title", "Go");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
}catch(Exception e){
e.printStackTrace();
}
//pDialog.dismiss();
pd.dismiss();
}
}
Your Adapter class
public class GoArrayAdapter extends ArrayAdapter<GoModelAll> {
private final Context context;
ImageLoader imgLoader;
private final ArrayList<GoModelAll> values;
DataHelper dh;
public GoArrayAdapter(Context context,
ArrayList<GoModelAll> values) {
super(context, R.layout.go_row, values);
this.context = context;
this.values = values;
imgLoader = new ImageLoader(context);
dh = new DataHelper(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.go_row, parent, false);
/** Get view over here.. */
GoModelAll asm = values.get(position);
TextView title = (TextView) rowView.findViewById(R.id.go_tv);
ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image);
ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red);
if(asm.isSeen)
{
go_red.setVisibility(View.INVISIBLE);
}
/**Set view over here..*/
title.setText(asm.title);
// Loader image - will be shown before loading image
int loader = R.drawable.image_not_available;
String image_url = asm.thumsrc;
imgLoader.DisplayImage(image_url, loader, business_logo);
return rowView;
}
}
At last your Model class
public class GoModelAll {
public String description = "";
public String excert = "";
public String thumsrc = "";
public String title = "";
public int postid = 0;
public boolean isSeen = false;
}
Show us your adapter code as well and try not to change an item of list view from setOnItemClickListener instead change your data and notify adapter to refresh the view.
Set this as background to your list item :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/white" />
<item android:color="#color/black" />
</selector>

Categories

Resources