This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 6 years ago.
So here I have class ListProductActivity.java that display list of products based on the search criteria entered by user and the data are retrieve from MySQL server using Json. My question is, how can I pass a single value (productName in this case) when user select from the listview to another activity so that I can use that value in the new Activity (viewProductActivity.java).
ListProductActivity.java
public class ListProductActivity extends AppCompatActivity {
private ListView list;
private ProgressDialog loading;
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_product);
list = (ListView) findViewById(R.id.listView);
productList = new ArrayList<HashMap<String,String>>();
getData();
}
public void getData(){
String s = getIntent().getStringExtra("productName");
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL2 + s;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showList(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListProductActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showList(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray(Config.JSON_ARRAY);
for(int i=0;i<products.length();i++){
JSONObject productData = products.getJSONObject(i);
String name = productData.getString(KEY_NAME);
String price = productData.getString(KEY_PRICE);
String brand = productData.getString(KEY_BRAND);
HashMap<String,String> product = new HashMap<String,String>();
product.put(KEY_NAME,name);
product.put(KEY_PRICE,price);
product.put(KEY_BRAND,brand);
productList.add(product);
}
ListAdapter adapter = new SimpleAdapter(
ListProductActivity.this, productList, R.layout.list_product,
new String[]{KEY_NAME,KEY_PRICE,KEY_BRAND},
new int[]{R.id.name, R.id.price, R.id.brand}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So, what function can I implement in my ListProductActivity class to pass the productName based on user selected in the listView to another activity and how to receive the passing value in viewProductActivity class?
I really hope you guys can post the function and briefly explain on how it works, so that I can understand the codes really well. Comment at the codes will be more clear and helpful. Thank You.
Edited
Here is the picture of the result from the listview after searching
Click To View Image
First simply implement onItemClickListener of listview on current activity
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String product_name = productList.get(position).get(KEY_NAME);
Intent intent = new Intent(YourCurrentActivity.this,YourNextActivity.class);
intent.putExtra("product_name",product_name);
startActivity(intent);
}
});
and receive that value in onCreate method of YourNextActivity.java like this:
Bundle bundle = getIntent().getExtras();
String productname = bundle.getString("product_name");
Implement like this,
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = productList.get(position).get(KEY_NAME);
Intent i;
i = new Intent(mContext, viewProductActivity.class);
i.putExtra("productName",name);
startActivity(i);
}
});
Pass the array list to the new activity later you can use whatever you want from that extra
eg:-
Intent i = new Intent(ctx, SecondActivity.class);
i.putExtra("List", List); //List is an arraylist like yours
startActivity(i);
Second activity:
SList = (ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("List");
Now use whatever you want using SList.get(0).get("keyname")
put your code here
private void showList(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray(Config.JSON_ARRAY);
for(int i=0;i<products.length();i++){
JSONObject productData = products.getJSONObject(i);
String name = productData.getString(KEY_NAME);
String price = productData.getString(KEY_PRICE);
String brand = productData.getString(KEY_BRAND);
HashMap<String,String> product = new HashMap<String,String>();
product.put(KEY_NAME,name);
product.put(KEY_PRICE,price);
product.put(KEY_BRAND,brand);
productList.add(product);
}
ListAdapter adapter = new SimpleAdapter(
ListProductActivity.this, productList, R.layout.list_product,
new String[]{KEY_NAME,KEY_PRICE,KEY_BRAND},
new int[]{R.id.name, R.id.price, R.id.brand}
);
list.setAdapter(adapter);
// put your new code here
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String product_name = productList.get(position).get(KEY_NAME);
Intent intent = new Intent(YourCurrentActivity.this,YourNextActivity.class);
intent.putExtra("product_name",product_name);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
You can pass it via Intent in your listview adapter as
Intent i;
i = new Intent(mContext, viewProductActivity.class);
i.putExtra("productName",whateverstring);
mContext.startActivity(i);
Related
from my question above, I actually want to test the existing codes that I from the Internet. I succesffuly can grab the data from a column in a table and shows back the data. For example, I when i choose person name's "Lim AI Khoon" the it wil display Lim Ai Khoon Names, and also Lim Ai Khoon's badge ID on the same activity. Now, how can I save the data that had being selected to sharedPreferences and display the data at next activity? Below is my code
//MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
tvName = (TextView) findViewById(R.id.tvName);
tvBadgeID = (TextView) findViewById(R.id.tvBadgeID);
btnNext = findViewById(R.id.btnNext);
//This method will fetch the data from the URL
getData();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("reviewer",spinner.getSelectedItem().toString());
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_BADGEID);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
tvName.setText(getName(position));
tvBadgeID.setText(getCourse(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
tvName.setText("");
tvBadgeID.setText("");
}
//Config.java
public class Config {
//JSON URL
public static final String DATA_URL = "http://10.0.2.2/spinner/getData.php";
//Tags used in the JSON String
public static final String TAG_NAME = "name";
public static final String TAG_BADGEID = "badgeid";
//JSON array name
public static final String JSON_ARRAY = "result";}
You missed one step,after this
editor.putString("reviewer",spinner.getSelectedItem().toString());
you need save the change ,put this line below :
editor.commit();
with that should work.
I'm new to Android development and Java in general, so I was wondering if someone could point me in the right direction.
I'm writing a currency convertor app and using Volley requests to send a request to an API to retrieve conversion rates.
Right now I am hardcoding the countries into the URL, which works as the conversion rate is successfully retrieved and displayed. I have two Spinners right now and the goal is to retrieve the string value of the selected Spinner value and then use those values for the json request.
I've created two setOnItemSelectedListeners for both Spinners and set the variable containing the value of the string to that. However, I'm getting an null object reference.
Here is what I have:
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
Double conversionDouble;
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
private Button convertBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnToSpinner();
addListenerOnButton();
jsonSendRequest();
Button convertBtn = (Button) findViewById(R.id.convertBtn);
final EditText fromAmountEditText = findViewById(R.id.fromAmountEditText);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView toAmountTextView = findViewById(R.id.toAmountTextView);
DecimalFormat percentageFormat = new DecimalFormat("0.00");
Double fromAmount = Double.parseDouble(fromAmountEditText.getText().toString());
String result = "$" + percentageFormat.format(conversionDouble*fromAmount);
toAmountTextView.setText(result);
}
});
rq = Volley.newRequestQueue(this);
}
public void jsonSendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
// String url = "http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
String url = "http://free.currencyconverterapi.com/api/v3/convert?q=" + fromSpinnerText + "_" + toSpinnerText + "&compact=ultra";
// Request a string response
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonobject = null;
try {
jsonobject = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonobject.has(fromSpinnerText + "_" + toSpinnerText)) {
try {
conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
// conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void addItemsOnToSpinner(){
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
List<String> currency = new ArrayList<String>();
currency.add("USD");
currency.add("CAD");
currency.add("CNY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, currency
);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(dataAdapter);
fromSpinner.setAdapter(dataAdapter);
fromSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fromSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String toSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void addListenerOnButton() {
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Button convertBtn = (Button) findViewById(R.id.convertBtn);
}
}
Any help is appreciated.
You have declared a few class variables related to your Spinner:
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
You have also correctly defined the onItemSelected() method for the setOnItemSelectedListener.
But, I assume you meant to make the class variables Spinner toSpinnerText, fromSpinnerText; to actually be:
String toSpinnerText = "";
String fromSpinnerText= "";
So that you could call:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fromSpinnerText = (String) parent.getItemAtPosition(position);
}
Notice that the variable fromSpinnerText in the method is now using the class variable instead of the local variable you defined inside the onItemSelected() method.
The same goes for the onItemSelected() method for the other Spinner and toSpinnerText.
I use Volley in the onCreate of my Activity which gets a string on my server, then I convert this string to an arraylist,checkedContactsAsArrayList, and I pass it over to my custom adapter using sharedpreferences, which does stuff with the arraylist in the listview.
But the custom adapter keeps getting the previous arraylist in sharedpreferences, not the one I've just got from the server. The Volley call is too late or something - I can see in logcat the latest values are put after they are got, if you know what I mean.
For example:
VolleyCall 1 putString: 1,2,3
VolleyCall 2 putString: 4,5,6
VolleyCall 3 putString: 7,8,9
Custom Adapter 1 getString: gets values of the last time app was used
Custom Adapter 2 getString: 1,2,3
Custom Adapter 3 getString: 4,5,6
Any idea how to fix this? I could try doing the Volley call in the getView of my custom adapter but I've read on Stackoverflow that's bad practice.
Here are the relvant parts of my code - I've slimmed it down a bit, as there's a lot of stuff in there irrelevant to this issue.
Here's the code of my activity, ViewContact:
public class ViewContact extends AppCompatActivity implements android.widget.CompoundButton.OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_view_contact);
//selectPhoneContacts is an empty array list that will hold our SelectPhoneContact info
selectPhoneContacts = new ArrayList<SelectPhoneContact>();
listView = (ListView) findViewById(R.id.listviewPhoneContacts);
StringRequest stringRequest = new StringRequest(Request.Method.POST, ViewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//toast the response of ViewContact.php, which has been converted to a
//JSON object by the Php file with JSON encode
Toast.makeText(ViewContact.this, "OnResponse is" + response, Toast.LENGTH_LONG).show();
System.out.println("ViewContact: And the response is " + response);
try {
//checkedContacts is a String
String checkedContacts = responseObject.getString("checkedcontacts");
//convert the checkedContacts string to an arraylist
checkedContactsAsArrayList = new ArrayList<String>(Arrays.asList(checkedcontacts.split(",")));
System.out.println("ViewContact: checkedContactsAsArrayList is " + checkedContactsAsArrayList);
//we want to bring the checkedContactsAsArrayList array list to our SelectPhoneContactAdapter.
// It looks like Shared Preferences
//only works easily with strings so best way to bring the array list in Shared Preferences is with
//Gson.
//Here, we PUT the arraylist into the sharedPreferences
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
editorcheckedContactsAsArrayList.commit();
System.out.println("ViewContact: jsoncheckedContactsAsArrayList is " + jsoncheckedContactsAsArrayList);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewContact.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//we are posting review_id into our ViewContact.php file, which
//we get when a row is clicked in populistolistview
//to get matching details
params.put("review_id", review_id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//checkBoxforContact.setChecked(true);
}
//******for the phone contacts in the listview
// Load data in background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
//we want to delete the old selectContacts from the listview when the Activity loads
//because it may need to be updated and we want the user to see the updated listview,
//like if the user adds new names and numbers to their phone contacts.
selectPhoneContacts.clear();
SelectPhoneContact selectContact = new SelectPhoneContact();
selectContact.setName(phoneNameofContact);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectPhoneContactAdapter(selectPhoneContacts, ViewContact.this,0);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onResume() {
super.onResume();
// getPrefs();
ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();
Toast.makeText(ViewContact.this, "resuming!", Toast.LENGTH_SHORT).show();
}
}
And my custom adapter, SelectPhoneContactAdapter :
public class SelectPhoneContactAdapter extends BaseAdapter {
//define a list made out of SelectPhoneContacts and call it theContactsList
public List<SelectPhoneContact> theContactsList;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectPhoneContact> arraylist;
Context _c;
ArrayList<String> MatchingContactsAsArrayList;
ArrayList<String> checkedContactsAsArrayList;
ArrayList <String> allNamesofContacts;
String contactToCheck;
//we will run through different logic in this custom adapter based on the activity that is passed to it
private int whichactivity;
String phoneNumberofContact;
String[] phoneNumberofContactStringArray;
String ContactsString;
Intent intent;
public SelectPhoneContactAdapter(final List<SelectPhoneContact> selectPhoneContacts, Context context, int activity) {
theContactsList = selectPhoneContacts;
_c = context;
this.arraylist = new ArrayList<SelectPhoneContact>();
this.arraylist.addAll(theContactsList);
whichactivity = activity;
//we are fetching the array list checkedContactsAsArrayList, created in ViewContact.
//with this we will put a tick in the checkboxes of contacts the review is being shared with
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(_c);
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
Type type2 = new TypeToken<ArrayList<String>>() {
}.getType();
checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
System.out.println("SelectPhoneContactAdapter checkedContactsAsArrayList :" + checkedContactsAsArrayList);
}
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public Object getItem(int i) {
return arraylist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
static class ViewHolder {
//In each cell in the listview show the items you want to have
//Having a ViewHolder caches our ids, instead of having to call and load each one again and again
TextView title, phone;
CheckBox check;
Button invite;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
//this is the SelectPhoneContact object; consists of textboxes, buttons, checkbox
final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);
ViewHolder holder = null;
if (convertView == null) {
//if there is nothing there (if it's null) inflate the view with the layout
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.phone_inflate_listview, null);
holder = new ViewHolder();
//So, for example, title is cast to the name id, in phone_inflate_listview,
//phone is cast to the id called no etc
holder.title = (TextView) convertView.findViewById(R.id.name);
holder.phone = (TextView) convertView.findViewById(R.id.no);
holder.invite = (Button) convertView.findViewById(R.id.btnInvite);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//in the listview for contacts, set the name
holder.title.setText(data.getName());
//in the listview for contacts, set the number
holder.phone.setText(data.getPhone());
holder.check.setTag(data);
return convertView;
}
}
Call this: loadContact.execute();
After you call .commit();
ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();
i want to implements this method into my coding,but i dont know how to do it,can someone give me some suggestion on how to do it?
Below is the screenshot the coding that i want to use.
View.ONItemClickListener
this is my coding.
ViewOrder.java
public class ViewOrder extends AppCompatActivity implements ListView.OnItemClickListener {
public static final String JSON_URL = "http://dashberry.com/strack/mobile/viewOrder.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL, new Response.Listener<String>() {
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewOrder.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.itemName,ParseJSON.origin,ParseJSON.destination);
listView.setAdapter(cl);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ItemDetail.class);
//ParseJSON<String> map = (ParseJSON)parent.getItemAtPosition(position);
//HashMap<String,String> map = (HashMap)parent.getItemAtPosition(position);
// String empId = map.get(ParseJSON.itemName).toString();
// intent.putExtra("item_id", empId);
startActivity(intent);
}
}
ParseJSON.java
public class ParseJSON {
public static String[] itemName;
public static String[] origin;
public static String[] destination;
public static final String JSON_ARRAY = "result";
public static final String KEY_NAME = "itemName";
public static final String KEY_ORIGIN = "origin";
public static final String KEY_DESTINATION = "destination";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
itemName = new String[users.length()];
origin = new String[users.length()];
destination = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
itemName[i] = jo.getString(KEY_NAME);
origin[i] = jo.getString(KEY_ORIGIN);
destination[i] = jo.getString(KEY_DESTINATION);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So basically what i want is when user click the item in the list,it will take the user to the next activity with some data(itemName).
implement onItemClick like
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ItemDetail.class);
//you can putExtra only position or id
intent.putExtra("position", position);
intent.putExtra("id", id);
startActivity(intent);
}
You Should Create Anther Activity called ItemDetail you can get id and position by add this code in onCreate() to know which item was clicked
Intent intent = getIntent();
String position = intent.getStringExtra("position");
String id = intent.getStringExtra("id");
I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}