How to populate AlertDialog from Arraylist.
My Arraylist something like this :
{ Brand=Weber,
Category=Urethane,
Code=Wpu-01,
Description=Black,
Quantity=5;
Brand=Weber,
Category=Urethane,
Code=Wpu-02,
Description=White,
Quantity=10}
And I want to show that in alertdialog is something like this
Product Details
Weber Urethane Wpu-01 Black 5
Weber Urethane Wpu-02 White 10
then a button ("CLOSE")
Please help me . Thanks in advance.
This the code
public void updateJSONdata() {
orderlist = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl(PRODUCTLIST_URL);
try {
order = json.getJSONArray(GET_PRODUCT);
for (int i = 0; i < order.length(); i++) {
JSONObject c = order.getJSONObject(i);
String id = c.getString(GET_ID);
String brand = c.getString(GET_BRAND);
String category = c.getString(GET_CATEGORY);
String description = c.getString(GET_DESCRIPTION);
String code = c.getString(GET_CODE);
String quantity = c.getString(GET_QUANTITY);
String unit = c.getString(GET_UNIT);
String unitprice = c.getString(GET_UNITPRICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(GET_ID,id);
map.put(GET_BRAND, brand);
map.put(GET_CATEGORY, category);
map.put(GET_DESCRIPTION, description);
map.put(GET_CODE, code);
map.put(GET_QUANTITY, quantity);
map.put(GET_UNIT, unit);
map.put(GET_UNITPRICE, unitprice);
orderlist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
StringBuilder sb = new StringBuilder();
for (HashMap<String,String> product:orderList){
for (Map.Entry entry:product.entrySet()){
sb.append(entry.getValue()).append(" ");
}
}
String msg = sb.toString();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Product details")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
To iterate through your ArrayList with HashMap and show the data on an AlertDialog, try something like:
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
StringBuilder sb = new StringBuilder();
for (HashMap map : list) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sb.append(((Map.Entry) it.next()).getValue()).append(" ");
}
sb.append("\n"); // Use this if you want a line break.
}
String msg = sb.toString();
new AlertDialog.Builder(this)
.setTitle("Product details")
.setCancelable(false)
.setMessage(msg)
.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do something.
dialogInterface.dismiss();
}
}).show();
This will show all the information in one AlertDialog.
If you really want to show them all in one single line, remove this line of code:
sb.append("\n"); // Use this if you want a line break.
Related
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...
In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.
Thanks for helping
Also some of my code is like this:
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
for (int i = 0; i < list.size(); i++) {
items[i] = list.get(i).getColumnEbat();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Segment seçiniz");
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(items[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
This is my image of result
Use this -
segmentDao.queryBuilder().distinct().where().eq("name", "value").query();
Hi I solved my problem with below code. Maybe you can say this is long way for this. I wrote my code like below because i couldn't do other ways(using .distinct() method in ORMLite or other ORMLite's method)
If you have any other ways to solve this, i am waiting your suggestions. Thanks for everybody, happy coding...
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
GenericRawResults<String[]> rawResults = segmentDao.queryRaw("SELECT DISTINCT Ebat FROM Segment WHERE Segment = ? ", editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
int i = 0;
for (String[] resultColumns : rawResults) {
String author = resultColumns[0];
items[i] = author;
i++;
}
int newLenght = 0;
for (int j = 0; j < items.length; j++) {
if (items[j] != null) {
newLenght++;
}
}
final CharSequence newItems[] = new CharSequence[newLenght];
for (int j = 0; j < newLenght; j++) {
if (items[j] != null) {
newItems[j] = items[j];
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Segment");
builder.setSingleChoiceItems(newItems, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(newItems[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
i'm trying to parse data from one Activity to the Other.
The data which i would like to parse are from the following HashMap:
ImageButton map = (ImageButton) findViewById(R.id.mapbtn);
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Locations.this, MapsActivity.class);
for (final HashMap<String, String> contact : contactList) {
String names = contact.get("name");
String str = contact.get("street");
String post = contact.get("postalcode");
String open = contact.get("opening");
String entr = contact.get("entry");
String age = contact.get("agegroup");
String bag = contact.get("background");
String prevbild = contact.get("imageurl");
String fsk = contact.get("Fsk");
i.putExtra("name", names);
i.putExtra("postal", post);
i.putExtra("street", str);
i.putExtra("opening", open);
i.putExtra("entry", entr);
i.putExtra("agegroup", age);
i.putExtra("background", bag);
i.putExtra("imageurl", prevbild);
i.putExtra("fsk", fsk);
}
startActivity(i);
}
});
This is working fine, but i dont know how i can get the data at the other activity. I tried the following but it doesnt work:
for (final HashMap<String, String> contact : contactList) {
String names = getIntent().getStringExtra("name");
Toast.makeText(getApplicationContext(),names, Toast.LENGTH_LONG).show();
}
Thanks
I'm trying to retrieve data from a array to a textfield, which is in a listview, right now i have this
txtDesignacao.setText(position + 1 + todasAsCategorias.toString());
And it's working:
The thing is, I just want the "Designacao" field, which in this case wold be "Azeites & Outros", how can I achieve this?
##########################Edit
TodasAsCategorias.class:
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String url1 = "something";
String url2 = "something2";
for (int idCat = 0; idCat <100; idCat++){
final String jsonStr = sh.makeServiceCall(url1 + idCat + url2);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
String K_PRODUTO = jsonObject.getString("K_PRODUTO");
String Designacao = jsonObject.getString("Designacao");
HashMap<String, String> cat = new HashMap<>();
cat.put("K_PRODUTO", K_PRODUTO);
cat.put("Designacao", Designacao);
listaCategorias.add(cat);
} catch (final JSONException e) {
//DO SOMETHING
}
} else {
//DO SOMETHING
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter = new ListViewAdapter(mContext);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do Something
}
});
}
}
public static ArrayList<HashMap<String, String>> getListaCategorias() {
return listaCategorias;
}
ListViewAdapter.class:
#Override
public void fillValues(int position, View convertView) {
ArrayList array = TodasAsCategorias.getListaCategorias();
Object todasAsCategorias = array.get(i);
TextView txtDesignacao = (TextView) convertView.findViewById(R.id.Designacao);
txtDesignacao.setText(position + 1 + todasAsCategorias.toString());
}
you have have todasAsCategorias as an object. just todastAsCate.Designacao if it's public property, or todastAsCate.getDesignacao(). All you have to do is check ur todasAsCategorias object
How would I go about parsing this JSON object and getting the "groups" array in Java on Android.
{ "groups": [ "Total_Social_Beta_Testers", "Test_Group" ] }
Here's my code:
LoginActivity.java
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String username = jsonResponse.getString("username");
String email = jsonResponse.getString("email");
String gender = jsonResponse.getString("gender");
String country = jsonResponse.getString("country");
String verified = jsonResponse.getString("verified");
String avatar = jsonResponse.getString("avatar");
//String group = jsonResponse.getString("groups");
int numlength = 0;
int CI = 0;
JSONArray jsonArrayGR = jsonResponse.getJSONArray("groups");
//String array of 500 spots
String rows = "";
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows = jsonArrayGR.getString(i);
}
//int rows = jsonResponse.getInt("rows");
//Starting Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent. addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("username", username);
intent.putExtra("email", email);
intent.putExtra("gender", gender);
intent.putExtra("country", country);
intent.putExtra("verified", verified);
intent.putExtra("avatar", avatar);
intent.putExtra("groups", rows);
//intent.putExtra("rows", rows);
session.createUserSession(
username,
email,
gender,
country,
verified,
avatar,
rows
);
Toast.makeText(getBaseContext(), "Login succeed, welcome!" , Toast.LENGTH_LONG).show();
//Adding a new flag to start the activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
LoginActivity.this.startActivity(intent);
_loginButton.setEnabled(true);
finish();
} else {
onLoginFailed();
}
}
catch (JSONException e){
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(e, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
UserSession.java
public void createUserSession(
String name,
String email,
String gender,
String country,
String verified,
String avatar,
String groups){
//Storage_Start session
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
//Storage of the email in pref
editor.putString(KEY_EMAIL, email);
//Storing the gender
editor.putString(KEY_GENDER, gender);
//Storing the country
editor.putString(KEY_COUNTRY, country);
//Storing the verified
editor.putString(KEY_VERIFIED, verified);
//Storing avatar
editor.putString(KEY_AVATAR, avatar);
//Storing groups
editor.putString(KEY_GROUPS, groups);
//Storing the gRows
//editor.putInt(INT_GROUPS, numlength);
//commit changes
editor.commit();
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
//gender
user.put(KEY_GENDER, pref.getString(KEY_GENDER, null));
//country
user.put(KEY_COUNTRY, pref.getString(KEY_COUNTRY, null));
//verifed?
user.put(KEY_VERIFIED, pref.getString(KEY_VERIFIED, null));
//Avatar
user.put(KEY_AVATAR, pref.getString(KEY_AVATAR, null));
//Groups
user.put(KEY_GROUPS, pref.getString(KEY_GROUPS, null));
// return user
return user;
}
UPDATE
This is where I am storing the values into the recyclerview:
public class ChatsAdapter extends RecyclerView.Adapter<ChatsAdapter.MyViewHolder> {
private List<Groups> chatlist;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView group;
public MyViewHolder(View view) {
super(view);
group = (TextView) view.findViewById(R.id.groups);
}
}
public ChatsAdapter(List<Groups> chatlist){
this.chatlist = chatlist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_row_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Groups groups = chatlist.get(position);
holder.group.setText(groups.getTitle());
}
#Override
public int getItemCount() {
return chatlist.size();
}
}
And this is how I am defining the strings:
public class Groups {
private String groups = "";
public Groups() {
}
public Groups(String groups) {
this.groups = groups;
}
public String getTitle() {
return groups;
}
}
This is how I am displaying the values set by the adapter (above) in my main activity:
//groups
String g = user.get(UserSessionManager.KEY_GROUPS);
String numrows = user.get(UserSessionManager.INT_GROUPS);
//String grows = user.get(UserSessionManager.INT_GROUPS);
int rows = Integer.parseInt(numrows);
Groups groups = new Groups(g);
groupslist.add(groups);
chatsAdapter.notifyDataSetChanged();
i believe here you must be facing problem
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows = jsonArrayGR.getString(i);
}
this is because you are not appending rows value in each loop, instead you are over writing the previous values.
easy solution
rows = jsonArrayGR.getString(i)+rows;
best solution
StringBuilder rows = new StringBuilder();
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows.append(jsonArrayGR.getString(i));
}
and finally use it in your code
intent.putExtra("groups", rows);
P.S. if you want to use rows as String later, just use String rows = rows.toString();
i hope this will surely help you :D
You should make a ArrayList<String> from this JSONArray and use this List to fill your RecyclerView,
ArrayList<String> listdata = new ArrayList<String>();
if (jArray != null) {
for (int i=0;i<jArray.length();i++)
listdata.add(jsonArrayGR.getString(i));
}
Now you can send this List to your MainActivity and fill your RecyclerView, which is required by you.
In current Activity ->
Bundle extra = new Bundle();
extra.putSerializable("list", listdata);
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("extra", extra);
In Mainactivity ->
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Object> objects = (ArrayList<Object>) extra.getSerializable("objects")
in your app.gradle, add this line under dependencies
compile 'com.google.code.gson:gson:2.3'
and the sync your project.
Now create a .java file with name GroupsModal.java
add this in your GroupsModal.java file
private Groups groups;
//getters and setters
Now create a .java file with name Groups.java and add these lines :
private String Total_Social_Beta_Testers;
//getters and setters
now in your loginActivity.java
#Override
public void onResponse(String response) {
GroupsModal groupsModal = gson.fromJson(response, GroupsModal.class);
if(groupsModal.getSuccessResponse == 200){
// successfully logged in
/*
* you can create classes and variables according to your JSON here
* for gson.fromJson,
* define at the top of loginActivity,
* private Gson gson = new Gson();
*/
}
}
Hope it helps..
String[] getStringArray(String name, JSONObject object) throws JSONException {
JSONArray jsonArray = object.getJSONArray(name);
String[] array = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
array[i] = jsonArray.getString(i);
}
return array;
}
Who would of thought getting a dialog box to show would be so difficult. In C# it is so easy. I've looked all over line for help and every tip seems to cause me trouble than good. Can someone please look at the below code and tell me where I might have gone wrong?
What I want is very simple. User clicks button. Then list appears. Then user clicks on one of the items in list, and dialogue appears. The code in onItemClick in the listview event is from someone else. It apparently works for that person. I keep clicking and seeing nothing. I'm open to suggestions on how to fix it, or new code all together. Sorry, the log has no error messages.
Please be specific about where I put the code as I'm an Android noob. And thank you in advance!
public class SetPrediction extends Activity
{
Button btnInsrt, btnFTeam, btnSTeam;
ArrayList<NameValuePair> nameValuePairs;
TextView txtGameTeams;
Bundle recdData;
String game;
JSONArray jArray;
String result;
InputStream is;
StringBuilder sb;
ArrayList<String> fNames;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.set_prediction);
nameValuePairs = new ArrayList<NameValuePair>();
txtGameTeams = (TextView) findViewById(R.id.txtGameTeams);
recdData = getIntent().getExtras();
game = recdData.getString("xxxx.xxxx.xxx");
txtGameTeams.setText("xxxxxxx: " + game + " game.");
btnInsrt = (Button) findViewById(R.id.btnInsert);
btnFTeam = (Button) findViewById(R.id.btnFirstTeam);
btnSTeam = (Button) findViewById(R.id.btnSecondTeam);
btnFTeam.setText(removeSpaces(game.split("vs")[0]));
btnSTeam.setText(removeSpaces(game.split("vs")[1]));
btnSTeam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("players", removeSpaces(game.split("vs")[1])));
fNames = new ArrayList<String>();
listView = (ListView) findViewById(R.id.lstPlayerForPrediction);
//http post
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/getTeamPlayers.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
}
//parse json data
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
fNames.add(jArray.getJSONObject(i).getString("First_Name"));
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SetPrediction.this, android.R.layout.simple_list_item_1, fNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View predictView, int item, long arg3)
{
final CharSequence[] items = {"Online", "Away", "Do not distrub","Invisible","Offline"};
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this);
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
public String removeSpaces(String s)
{
StringTokenizer st = new StringTokenizer(s," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
return t;
}
The problem is in the listView.setOnItemClickListener(new OnItemClickListener() event. That the part that doesn't work.
Check out this:
public void showAlertDialog(String title, String message, Context context)
{
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
Try using these code instead of your code just a minor change:::
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this).create();
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.show();
also import the following :::
import android.app.AlertDialog;
import android.content.DialogInterface;