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
}
}
Related
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();
}
Looks like find the image but i don't know how to insert into the simple adapter (or anything that let me set the image in my layout)
https://gyazo.com/61ab064c19ae50090f08e6436776a52e
I want to set an image for each object in the array, like:
monsterimglist.setImageResource(R.mipmap.icon_name);
For the moment im testing to show R.mipmap.a1 in all the array items in the listview.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
Someone can help me? Thanks a lot
ListView monsterslistview;
ImageView monsterimg;
TextView monstername;
TextView monstertype;
private static String monsterid;
ArrayList<HashMap<String, String>> MonstersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// FunciĆ³ llegir json
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show();
}
}
Close the Bracket before creating the adapter.May be it will change your result.
Updated :
ListView monsterslistview; ImageView monsterimg; TextView monstername; TextView monstertype;
private static String monsterid; ArrayList<HashMap<String, String>> MonstersList;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
} //-----This Bracket was missed in your code
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// FunciĆ³ llegir json public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json; }
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show(); }
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);
?>
So, i plan to make a listview that if one of its item clicked, it goes to other activity. it's obvious that i want to use intent with extras.
But in my code, the extras is not reffering.
I tried to refer the extras with exact value, it worked, but if I put the extras to refer my object/variable, it won't work.
So far my code goes like this
public class bulan extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tagihan_list);
Intent i = getIntent();
final String no_pel = i.getStringExtra("no_pel");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("nopel", no_pel));
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSON json = new JSON();
JSONObject jobj = json.getJSON("http://10.0.2.2/KP/tagihan.php", pairs);
try {
int length = jobj.getInt("panjang");
for(int n = 1; n <= length; n++){
String m = Integer.toString(n);
JSONObject row = jobj.getJSONObject(m);
String id_tagihan = "No. tagihan : " + row.getString("id");
String bulan = row.getString("bulan");
String tahun = row.getString("tahun");
String tagihan = "Rp. " + row.getString("tagihan");
String status = row.getString("status");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id_tagihan", id_tagihan);
map.put("bulan", bulan);
map.put("tahun", tahun);
map.put("tagihan", tagihan);
map.put("status", status);
list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list,
new String[] {"id_tagihan","bulan","tahun","tagihan","status"}, new int[] {
R.id.id_tagihan, R.id.bulan, R.id.tahun, R.id.tagihan, R.id.status});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String sid = ((TextView) view.findViewById(R.id.id_tagihan)).getText().toString();
String snopel = no_pel;
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", sid);
i.putExtra("no_pel", snopel);
startActivity(i);
}
});
}
}
Like I explained before, it's this part
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", sid);
i.putExtra("no_pel", snopel);
startActivity(i);
that change my code to work if I write them like this
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", "00001");
i.putExtra("no_pel", "0620120001");
startActivity(i);
try
Intent i = new Intent(bulan.this, rincian.class);
Bundle b=new Bundle();
b.putString("id",sid);
b.putString("no_pel",snopel);
i.putExtras(b);
startActivity(i);
In your rincian class get the values as follows.
b=getIntent().getExtras();
String fri_id=b.getString("id");
String nopel=b.getString("no_pel");
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)