I am new in android.I am fetching data from mysql and showing it in listview.things are working fine but now i want to pass the value to intent when user click on listview(Row).I have implemented setOnItemClickListener.but the list view is dynamic so i am not getting how to get values and pass it to the intent.
Thanks in advance
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://notice.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
Inside your listview onItemClickListener
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("TAG_NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
To getdata in second activity at onCreate method
String data;
Intent in=getIntent();
if(in!=null && in.hasExtra("TAG_NAME")){
data=in.getStringArrayExtra("TAG_NAME");
}
you can set text from view
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
String personName = personList.get(position).get(TAG_NAME);
Intent i = new Intent(AdminNotice.this, YourNextActivity.class);
i.putExtra("person_name", personName);
startActivity(i);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
you can use bundle to pass you're data from intent.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
ModelClass obj = getItem(position);
String name = obj.getName();
String date = obj.getDate();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("date", date );
Intent in = new Intent(currentActivity.this,destinationActivity.class);
in.putExtras(b);
startActivity(in);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
and you can get it in your other activity by doing.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent in = getIntent();
Bundle b = in.getExtras();
String name = b.getString("name");
String date = b.getString("date);
}
with this approach you don't have to hit the database again to retrieve data and you're one query is saved.
similarly you can send just you're 'id' also if you want.
but if you just want to pass 'id' then #Nas method would be more sorted and easy.
Related
After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
I am developing an android app which functions like as follows
Admin creates the data and saves it into database then user access the same data through app when it comes down to showing the data to user i fetch the data from the database which admin has already saved i show the data in listview, and listview having buttons in each row when user click on button it dose not goes to next activity.When user will click on button in listview the activity should pass to next activity.How do i do this?
//java activity
public class MainActivity extends ActionBarActivity {
String myJSON;
SimpleAdapter adapter;
Button btn;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "sname";
private static final String TAG_PRICE = "sprice";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
// ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>();
ListView list, listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView_search);
btn = (Button) findViewById(R.id.button3_book);
personList = new ArrayList<HashMap<String, String>>();
getData();
// Listview on item click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent zoom=new Intent(parent.getContext(), Details.class);
parent.getContext().startActivity(zoom);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String sname = c.getString(TAG_NAME);
String sprice = c.getString(TAG_PRICE);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,sname);
persons.put(TAG_PRICE,sprice);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.search_item,
new String[]{TAG_NAME,TAG_PRICE},
new int[]{ R.id.textView8_sellernm, R.id.textView19_bprice}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(MainActivity.this,Details.class);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://example.com/User/reg/listview.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
Hi i am working on a code in which in a listview it shows up some details like name and price , which comes from MySQL database . Now when I want to click on that particular item in that listview, what i want is that I want to move in to next activity the layout to which will be the same , only the data keeps changing when an item is clicked.
Like when I click on the Name A , i want to open a new activity in whcih the name as well as its address pincode , phone number will be shown up in details .
I have fetched all the details in the listview and shown up some which i want there and the next are passed to the detailed activity .
But i am only getting the key in toast and settext of second activity that is "NameAddressPincodePhone_Number" not the values associated with them .
Please look at the code I have written. Please help
Activity with listview
public class Plumbers extends Activity {
String myJSON;
public static final String TAG_RESULTS="result";
public static final String TAG_NAME = "Name";
public static final String TAG_ADDRESS = "Address";
public static final String TAG_PINCODE = "Pincode";
public static final String TAG_PHONENUMBER = "Phone_Number";
public static final String TAG_DOB = "DOB";
public static final String TAG_AADHARNUMBER = "Aadhar_Number";
public static final String TAG_Price = "price";
public static final String TAG_Spl = "spl";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
EditText search;
Spinner spin;
protected Object adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
list = (ListView) findViewById(R.id.list1);
spin=(Spinner)findViewById(R.id.spinner1);
search = (EditText)findViewById(R.id.search);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String Name = c.getString(TAG_NAME);
String price = c.getString(TAG_Price);
String spl = c.getString(TAG_Spl);
HashMap<String,String> plumbers = new HashMap<String,String>();
plumbers.put(TAG_NAME,Name);
plumbers.put(TAG_Price,price);
plumbers.put(TAG_Spl,spl);
personList.add(plumbers);
}
final ListAdapter adapter = new SimpleAdapter(
Plumbers.this, personList, R.layout.plumber,
new String[]{TAG_NAME ,TAG_Spl,TAG_Price },
new int[]{R.id.Name , R.id.spl ,R.id.price}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
adapter.getItem(position);
Intent intent = new Intent(Plumbers.this, Plumber1.class);
intent.putExtra("Name", TAG_NAME);
intent.putExtra("Address", TAG_ADDRESS);
intent.putExtra("Pincode", TAG_PINCODE);
intent.putExtra("Phone_Number", TAG_PHONENUMBER);
startActivity(intent);
}
});
spin.setAdapter((SpinnerAdapter) adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.2.7/homerun/plumbers.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
Activity for next Details of an item
public class Plumber1 extends Activity {
ImageView img,call;
TextView pl1,nm,ad,phn,qu,pin;
String Name,Address,Pincode,Phone_Number;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plumber1);
img=(ImageView)findViewById(R.id.imag);
call=(ImageView)findViewById(R.id.call);
pl1=(TextView)findViewById(R.id.pl1);
nm=(TextView)findViewById(R.id.name);
ad=(TextView)findViewById(R.id.Address);
pin=(TextView)findViewById(R.id.Pincode);
phn=(TextView)findViewById(R.id.phn);
qu=(TextView)findViewById(R.id.quotation);
Intent intent = getIntent();
if (intent.getExtras() != null) {
Name = intent.getStringExtra("Name");
Address = intent.getStringExtra("Address");
Pincode = intent.getStringExtra("Pincode");
Phone_Number = intent.getStringExtra("Phone_Number");
Toast.makeText(getApplicationContext(), Name + "" + Address + "" + Pincode + "" + Phone_Number +"" , Toast.LENGTH_LONG).show();
}
nm.setText(Name+"");
ad.setText(Address+"");
pin.setText(Pincode+"");
phn.setText(Phone_Number+"");
call.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent in = new Intent(android.content.Intent.ACTION_DIAL, Uri
.parse("tel:+918058706096"));
startActivity(in);
}
});
}
}
Php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("homerun");
$sql="select * from plumbers WHERE Status = '1' GROUP BY price ORDER BY name ASC" ;
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($res)){
array_push($result,
array('Name'=>$row[1],'spl'=>$row[8],'price'=>$row[7]));
}
echo json_encode(array("result"=>$result));
mysql_close();
?>
This is wrong
intent.putExtra("Name", TAG_NAME);
putExtra have two arguments first one is of key and second one is of value.In your case first one is correct but in value argument again you are sending a TAG_NAME(which is wrong).
Use below code
intent.putExtra("Name",personList.get(position).get(TAG_NAME));
intent.putExtra("Address",personList.get(position).get(TAG_ADDRESS));
intent.putExtra("Pincode",personList.get(position).get(TAG_PINCODE));
intent.putExtra("Phone_Number",personList.get(position).get(TAG_PHONENUMBER));
startActivity(intent);
Just Copy Above Code
Also Update your for loop to below code
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String Name = c.getString(TAG_NAME);
String price = c.getString(TAG_Price);
String spl = c.getString(TAG_Spl);
String Address = c.getString(TAG_ADDRESS);
String Pincode = c.getString(TAG_PINCODE);
String Phone_Number = c.getString(TAG_PHONENUMBER);
HashMap<String,String> plumbers = new HashMap<String,String>();
plumbers.put(TAG_NAME,Name);
plumbers.put(TAG_Price,price);
plumbers.put(TAG_Spl,spl);
plumbers.put(TAG_ADDRESS,Address);
plumbers.put(TAG_PINCODE,Pincode);
plumbers.put(TAG_PHONENUMBER,Phone_Number);
personList.add(plumbers);
}
I am new in android,I have created a simple listview which is fetching data from mysql and every thing is working fine but now i want to pass the values of listview(Row) to another activity and when i am clicking on particular row i am getting null value.
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, Object> data = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
Intent intent = new Intent(getApplicationContext(), SingleMessage.class);
intent.putExtra("KEY", data);
startActivity(intent);
}
});
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
set the OnItemClickListener to the list view
public boolean onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
/ /write your code here to send data like
ModelClass obj = getItem(position);
String name = obj.getName();
Intent intent = new Intent(Activity.this, Activity2.class);
intent.putExtras("Name", name);
startActivity(intent);
}
or you can do like this way also
interfaceObj.sendData(obj);
I have an interesting fragment with multiple spinners. THe first spinner, loads the data into the second spinner based on what was selected. It looks something like this:
When the fragment first loads the first spinner is "All" and it fills the listView with all the beers. Right now this is the only listView I can click on items without them force closing. The code for my portfolio is:
public class Portfolio extends Fragment implements PortfolioGetAllBeers.OnArticleSelectedListener {
String beerId = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
final View theLayout = inflater.inflate(R.layout.activity_portfolio, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Portfolio");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
Log.d("portfolio", portfolioChoice);
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Brewery")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//todo: get breweries and fill spinner
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = ""myurl2;
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
else if (portfolioChoice.equals("Rating")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//make array
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("1");
tasteList.add("2");
tasteList.add("3");
tasteList.add("4");
tasteList.add("5");
// Selection of the spinner
Spinner spinner = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(selectedItemView.getContext(), android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//todo: add on select for spinner 2
//add on item selected
final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
final ListView lv = (ListView) theLayout.findViewById(R.id.allYourBeersList);
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myurl4;
Log.d("portfolio" , url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
// Inflate the layout for this fragment
return theLayout;
}
#Override
public void onArticleSelected(String bID, String brewery){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BeerPage();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
bundle.putString("breweryIDSent", brewery);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
If the spinner is all on the first load it runs this portion of code from above:
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
Which calls this async task to load the listview:
public class PortfolioGetAllBeers extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllBeers (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
//***************************code for on click
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString , String brewery);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
//*****************************end code for onClick
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
//todo: go to beer page
listener.onArticleSelected(tempID, tempBrewID);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
When this loads the listview with items the onclicks work correctly through the interface. I am having trouble how to do the interface for the other options when the second spinner loads the data into the listview.
For example if you select style in the first spinner and an option in the second spinner as shown in the picture I posted above. It runs down this if statement in the code from Portfolio above:
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
When PortfolioGetAllStyles asyc task is execute I am not sure how to set the onclick to the interface. The code for PortfolioGetAllStyles is:
public class PortfolioGetAllStyles extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllStyles (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("style");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "http://beerportfolio.com/app_getAllYourBeersStyle.php?u=" + userID + "&b=" + portfolioChoice;
Log.d("portfolio", url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
The error I am getting is:
03-03 14:30:00.495 20817-20817/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.PortfolioGetAllBeers$1.onItemClick(PortfolioGetAllBeers.java:114)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
In short I think I need to get these lines working to tie the OnSelectedListener from the portfolio page to this async task:
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
I just can not pass Portfolio.this into that line since we are not in Portfolio but another async task launched from it.
It seems that in this line:
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
You are creating and triggering async task witout setting listener. So you should do one of the following things:
set listener always before executing created async task
check if listener is not null before calling it:
if(listener != null){
listener.onArticleSelected(tempID, tempBrewID);
}