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.
Related
Using Android Studio, I created an activity which consists of a form that allows the user to add items to the database in the table which the user wishes. In terms of design, everything works well so far. I am using spinner in order to retrieve a particular column from a table and display the data in the spinner, however, whenever I run the application on Emulator/smartphone it does not display the data which I retrieved from the database (connection to the database was indeed successful and the data was outputted in json format in web browser). Any suggestions on this? Many thanks.
On a different laptop, a new android studio project was created and the code which I've shown here was run for testing purposes. Apparently, the spinner worked when I tried this, I have no idea why but I suspected different Gradle or Android studio versions?
public class add_activity extends AppCompatActivity {
private int PICK_IMAGE_REQUEST = 1;
private static final String typearray = "type_name";
private static final String type = "type_name";
private static final String JSON_ARRAY ="result";
private JSONArray result;
private Button btn_choose ;
Spinner spinner;
private ArrayList<String> arrayList;
TextView food_type;
String type_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
btn_choose = findViewById(R.id.btn_choosedesign);
this.spinner = (Spinner) findViewById(R.id.spinnertype);
food_type = (TextView) findViewById(R.id.hiddentype);
// findViewById(R.id.hiddentype).setVisibility(View.GONE);
arrayList = new ArrayList<String>();
getdata();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
food_type.setText(getlocation(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
food_type.setText("");
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
...
}
});
}
private void showFileChooser() {
...
}
private void getdata() {
StringRequest stringRequest = new StringRequest("http://.../.../gettype.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
details(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void details(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(typearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
this.spinner.setAdapter(new ArrayAdapter<>(add_activity.this, android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get location name which user selects
private String getlocation(int position) { // method is used to post name of marker to database accordingly
String loc = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching location from that object
loc = json.getString(type);
} catch (JSONException e) {
e.printStackTrace();
}
//Return location
return loc;
}
}
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();
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);
i want to set the background color of listview using java...
Below is the code in which i want to set the background color of list view.
value in the name,address,varificationtype comes from server.
now i want to set the background color of listview to RED.
I already defined
public class GetLead extends ListActivity implements OnClickListener{
private ProgressDialog pDialog;
// URL to get contacts JSON
// private static String url = "104.25.125.70/verification/getCaf";
// JSON Node names
private static final String TAG_ID = "cid";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
// private static final String TAG_CONTACTS = "contacts";
//
String priority="high";
private static final String TAG_ADDRESS = "address";
private static final String TAG_STATUS = "status";
private static final String TAG_VARTYPE = "verification";
private long backPressedTime = 0;
GlobalClass gclass;
// contacts JSONArray
JSONArray contacts = null;
Button refresh, logout;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_getjson);
// startService(new Intent(this, LocationBackgroundService.class));
contactList = new ArrayList<HashMap<String, String>>();
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 custid = ((TextView) view.findViewById(R.id.custId))
.getText().toString();
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.address))
.getText().toString();
String verType = ((TextView) view.findViewById(R.id.verificationType))
.getText().toString();
// Starting single contact activity
if(verType.equals("reside")){
Intent in = new Intent(getApplicationContext(),
resideVarStatusUpdate.class);
in.putExtra(TAG_ID, custid);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
}
else if(verType.equals("reside1")){
Intent in = new Intent(getApplicationContext(),
reside1VarStatusUpdate.class);
in.putExtra(TAG_ID, custid);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
}
}
});
// Calling async task to get json
new GetContacts().execute();
refresh = ((Button) findViewById(R.id.refresh));
refresh.setOnClickListener(this);
logout = ((Button) findViewById(R.id.logout));
logout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == refresh){
new GetContacts().execute();
}
else if (v == logout){
this.finish();
}
}
/**
* 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(GetLead.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String jsonStr = null;
// get user data from session
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("id",globalVariable.getId()));
// email
try {
jsonStr = SimpleHttpClient
.executeHttpPost(
"http://"+constantVar.ip+"/verification/getCaf",
postParameters);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String status = c.getString(TAG_STATUS);
String varType = c.getString(TAG_VARTYPE);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ADDRESS, address);
contact.put(TAG_STATUS, status);
contact.put(TAG_VARTYPE, varType);
contact.put("priority", priority);
// adding contact to contact list
contactList.add(contact);
}
} 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(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
R.id.name, R.id.address, R.id.verificationType});
if (priority.equals("high")) {
setListAdapter(adapter);
LinearLayout listLayout = (LinearLayout)findViewById(R.id.list_layout);
listLayout.setBackgroundColor(Color.GREEN);
}
}
}
How can I do this only using Java here?
Update your code in onPostExecute()
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
R.id.name, R.id.address, R.id.verificationType});
if (priority.equals("high")) {
GetLead.this.runOnUiThread(new Runnable() {
#Override
public void run() {
setListAdapter(adapter);
getListView().setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
});
}
}
You should do this in your adapter, override getView like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_event_row_view, parent, false);
convertView.setBackgroundColor(Color.RED);
Now you can set the color of each entry as you wish.
Actually you have to set the layout background color used in xml to set color accordingly.
if (priority.equals("high")) {
LinearLayout listLayout = listItem.findViewByid(R.id.list_layout);
listLayout.setBackground(R.color.Red)
setListAdapter(adapter);
}