Saving Android Preferences - android

Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}

In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)

Related

how to select first index in listview onCreate()? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...
public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qand_apractice);
questions = new ArrayList<>();
myqid = new ArrayList<>();
Bundle b = getIntent().getExtras();
setTitle(b.getString("subject"));
qsid = b.getString("qsid");
quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
listView = findViewById(R.id.lvquestions);
getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
.toString();
txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
.toString();
txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
.toString();
txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
.toString();
txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
.toString();
txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
.toString();
txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
.toString();
txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
.toString();
txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
.toString();
showQuiz();
}
});
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
}
this is the Error fetch in debug logcat..
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
at android.app.Activity.performCreate(Activity.java:6351)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.
Do Your Selection after you set Your Adapter to the Listview
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview.
Add this lines after adding the adapter.
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
or use
listView.setAdapter(adapter);
listView.setItemChecked(0, true)
This will show a toast message for first opening. This should be added after the adapter set.
Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}

how to show data that get from selected listview in another activity

i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>

Retrieving String[] from JSONObject from sharedPreferences

I was following Micers Answer store and retrieve a class object in shared preference
But how do I retrieve back STring[] from JSOnObject
my class is :
public class AppearExamState implements Serializable{
private static final long serialVersionUID = 1L;
Boolean flag = false;
int questionId;
int subjectId;
String[] storedAnswers;
public AppearExamState(int q, int subjId, String[] ans, boolean flg){
questionId = q;
subjectId = subjId;
storedAnswers = ans;
flag = flg;
} .......
.........getters and setters.....
.......
//-----------------------------------------------------------------
// Here I convert myObject to JsonObject
//-----------------------------------------------------------------
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Qid", this.questionId);
obj.put("Stored_Ans", this.storedAnswers);// is this RIGHT??
obj.put("subj_id", this.subjectId);
obj.put("Flag", this.flag);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Now when I store in sharepref I followed micers answer and did this:
//--------------------------------------------------------------------------------------
public void sendSharedPreference(ArrayList<AppearExamState> arrayl){
SharedPreferences mPrefs = this.getSharedPreferences("aimmds_state", 0);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Set<String> set= new HashSet<String>();
for (int i = 0; i < arrayl.size(); i++) {
set.add(arrayl.get(i).getJSONObject().toString());
}
prefsEditor.putStringSet("aimmds_state", set);
prefsEditor.commit();
}
//--------------------------------------------------------------------------------------
and I am stuck here with no clue how to do this
public ArrayList<AppearExamState> loadFromStorage(Context c) {
SharedPreferences mPrefs = c.getSharedPreferences("aimmds_state", 0);
ArrayList<AppearExamState> items = new ArrayList<AppearExamState>();
Set<String> set = mPrefs.getStringSet("aimmds_state", null);
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s);
int Quesid = jsonObject.getInt("Qid");
int SubjId = jsonObject.getInt("subj_id");
Boolean flag = jsonObject.getBoolean("Flag");
String[] StoAnswer = ????? ;
AppearExamState myclass = new AppearExamState(Quesid, SubjId, StoAnswer, flag );
items.add(myclass);
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
You cannot put an array to JSON, but you can put a Collection, which is represented by a JSONArray (http://www.json.org/javadoc/org/json/JSONObject.html#put%28java.lang.String,%20java.util.Collection%29). So the correct way to put your array to JSONObject is:
obj.put("Stored_Ans", new JSONArray(this.storedAnswers));
and to get:
JSONArray jsonArray = jsonObject.getJSONArray("Stored_Ans");
String[] StoAnswer = new String[jsonArray.length()];
for(i = 0; i < jsonArray.length(); i++){
StoAnswer[i] = jsonArray.getString(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>

Android listview header

i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}

Categories

Resources