Am getting the results as in dynamic buttons, but i want to display that in gridview.here is my code
JSONArray jsonMainNode1 = jsonResponse.getJSONArray("menu");
// JSONObject e = jsonMainNode1.getJSONObject(position);
int lengthJsonArr = jsonMainNode1.length();
for(int i=0; i <lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode1.getJSONObject(i);
String Pid = jsonChildNode.optString("pid".toString());
String Name = jsonChildNode.optString("name").toString();
String Refid=jsonChildNode.optString("refid".toString());
String resName = jsonChildNode.getString("image_url");
OutputData = Name;
str_id = Pid;
// OutputData += "pid : "+ Pid +" "+ "content : "+ Name+" ";
LinearLayout buttonContainer=(LinearLayout)findViewById(R.id.btn_container);
Button button = new Button(buttonContainer.getContext());
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
ViewGroup.LayoutParams params = button.getLayoutParams();
button.setLayoutParams(params);
//Button new width
params.width = 64;
params.height = 64;
button.setText(OutputData);
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
button.setBackgroundResource(resId);
button.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
button.setTextSize(13);
}
button.setTag(Refid);
button.setTextColor(Color.parseColor("#FF0000"));
buttonContainer.addView(button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LinearLayout buttonContainer = (LinearLayout)findViewById(R.id.btn_container);
buttonContainer.removeAllViews();
What is the amount of data in json?
Parse json and Get your data into a model class using Gson, refer:
Unable to Loop through dynamic json string recursively in android
And pass the ArrayList of the class objects to a custom adapter for the gridview, refer:
http://www.learn-android-easily.com/2013/09/android-custom-gridview-example.html
http://www.mkyong.com/android/android-gridview-example/
http://www.technotalkative.com/android-gridview-example/
Related
I'm creating a class called "partite", and this is the code
public class Partita {
String HT; //HomeTeam
String AT; //AwayTeam
String dataP; //dataPartita
int HG; //HomeGoal
int AG; //AwayGoal
String FTR; //Full time result
public Partita(){
this.HT = "";
this.AT = "";
this.dataP = "";
this.HG = 0;
this.AG = 0;
this.FTR = "";
}
public Partita(String HT, String AT, String dataP, int HG, int AG, String FTR) {
this.HT = HT;
this.AT = AT;
this.dataP = dataP;
this.HG = HG;
this.AG = AG;
this.FTR = FTR;
}
}
In the main activity I'm creating an ArrayList, putting a list of some "Partita" object, with attributes come from a json file, and then I create an ArrayMap and put the ArrayList inside, like this
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
partite.add(new Partita(jsonPart.getString("HomeTeam"),
jsonPart.getString("AwayTeam"),jsonPart.getString("Date"),
jsonPart.getInt("FTHG"), jsonPart.getInt("FTAG"),
jsonPart.getString("FTR")));
partitemap.put(i, partite.get(i));
Log.i("partita", partite.get(i).HT + " " + partite.get(i).HG + ":" + partite.get(i).AG + " " + partite.get(i).AT);
}
How can I use the ArrayMap instead of ArrayList to get the attributes of an object and use it?
Use this instead (edited):
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
partitemap.put(i, new Partita(jsonPart.getString("HomeTeam"),
jsonPart.getString("AwayTeam"),
jsonPart.getString("Date"),
jsonPart.getInt("FTHG"),
jsonPart.getInt("FTAG"),
jsonPart.getString("FTR")
)
);
Log.d("tag", partitemap.get(i).HT);
}
I want to get one array from PHP that one of the fileds is an array.
How can get basket's data with jsonArray and jsonObject ?
(In the code below, the basket is an array that contains 5 parameters).
It's my array:
[{"orderCode":11514,"orderDate":"2017/05/21","orderPrice":"19200","fullName":"Jack","address":"addr 1","cellphone":"09151515730","basket":[{"b_qty":"4","pid":"8","b_price":"9500","b_discount":"10","title":"obj1"}]
Edit
String b_price ="";
String b_discount="";
String b_qty ="";
String title= "";
String pid="";
try
{
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
JSONArray orderBasket = object.getJSONArray("basket");
for (int j = 0; j < orderBasket.length(); j++){
JSONObject object1 = orderBasket.getJSONObject(j);
b_qty = object1.getString("b_qty");
pid = object1.getString("pid");
b_price = object1.getString("b_price");
b_discount = object1.getString("b_discount");
title = object1.getString("title");
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.basketPrice.setText(b_price);
customOrderList.basketDiscount.setText(b_discount);
customOrderList.basketTitle.setText(title);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
//Now orderBasket is jsonArray
JSONArray orderBasket = object.getJSONArray("basket");
// So fetch all objects from orderBasket array
for (int j = 0; j < orderBasket.length(); j++){
JSONObject objectbsk = orderBasket.getJSONObject(j);
String b_qty = objectbsk.getString("b_qty");
String pid = objectbsk.getString("pid");
String b_price = objectbsk.getString("b_price");
String b_discount = objectbsk.getString("b_discount");
String title = objectbsk.getString("title");
// Create a orderBasket list for Basket with these keys also as you have created for CustomOrderList and use it
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.orderBasket.setText(orderBasket);
// here you can't do set text since it's jsonarray. So use basketlist to show the data`
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}
i mean editText created programmatically. I want to get the data inputted from those editText i created.
These are i've done so far.
VARIABLES
private GridLayout gridLayout;
//for tasks
int rowIndex = 2;
int colIndex = 1;
int rowIndex2 = 2;
int colIndex2 = 0;
int i=0;
int j=0;
//database variables
MyDBAdapter dbhandler;
To be able to create an editText in a gridlayout by a button click.
When "add new Task" button is clicked:
public void addTask(View view) {
i++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String tname = "task" + Integer.toString(i);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(tname);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30, 0, 0, 0);
textView.setTextColor(Color.BLACK);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("TASK "+Integer.toString(i)+": ");
editText.setId(i);
idsMap.put(tname, i);
}
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
this.j = 0;
}
When "Add new Subtask" button is clicked:
public void addSubtask(View view) {
j++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String taskno = "task" + Integer.toString(i) + "subtask" + Integer.toString(j);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(taskno);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30,0,0,0);
textView.setTextColor(Color.BLACK);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("Subtask "+Integer.toString(j)+": ");
editText.setId(j);
idsMap.put(taskno, j);
}
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
}
IT WOULD LOOK LIKE THIS FOR EXAMPLE:
TASK 1: ___________
Subtask 1: ________
Subtask 2: ________
TASK 2: ___________
Subtask 1: ________
TASK 3: ___________
Assuming the user is done inputting the necessary info and clicks the submit button. THE PROBLEM COMES IN. I DONT KNOW HOW TO GET ALL THE VALUES BASED on the number of editText created by the user.
public void submit(){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//implementation
String task1 = task1.getText().toString(); // It would only get task1
String subtask1 = task1subtask1.getText().toString(); // It would only get subtask1 of task 1
}
}
That kind of implementation is not usable since i dont know how many editTexts of tasks and subtasks that the user created. HELPPPP T___T
Every time you create an Edit Text use View.generateId() to generate an ID, store that ID in an HashMap or loop your container Views with getChildAt() and then, if its an EditText get its value.
Maybe you can set a custom tag for each edittext that you create.
You can determinate a specific generic tag for "Task" and an other for "Subtask" and after each creation, you set the tag to your edittext like that :
edittext.setTag(KEY, "task_X") where X is a incremental id.
After that, you can enumerate all children of your main container and check tags'children
List<EditText> allEdittext = new ArrayList<EditText>();
public void addSubtask(View view) {
j++;
Map<String, Integer> idsMap = new HashMap<String, Integer>();
String taskno = "task" + Integer.toString(i) + "subtask" + Integer.toString(j);
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(colIndex);
editText.setTextColor(Color.BLACK);
editText.setBackgroundResource(android.R.drawable.edit_text);
editText.setText(taskno);
editText.setLayoutParams(param);
TextView textView = new TextView(this);
GridLayout.LayoutParams param2 = new GridLayout.LayoutParams();
param2.rowSpec = GridLayout.spec(rowIndex2);
param2.columnSpec = GridLayout.spec(colIndex2);
textView.setPadding(30,0,0,0);
textView.setTextColor(Color.BLACK);
textView.setLayoutParams(param2);
if (rowIndex > 1) {
textView.setText("Subtask "+Integer.toString(j)+": ");
editText.setId(j);
idsMap.put(taskno, j);
}
allEdittext.add(editText);
gridLayout.addView(editText);
gridLayout.addView(textView);
rowIndex++;
rowIndex2++;
}
Then your get the values from the edit text
public void submit(){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//implementation
String task1 = task1.getText().toString(); // It would only get task1
//i will be the position
String subtask1 = allEdittext.get(i).getText().toString();// It would only get subtask1 of task 1
}
}
Like this you can modify the code for addtask() function
I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}
I want to insert images into dynamic buttons, I can get everything other than images. I want my button to display as text+image, but instead I am getting text + androidgraphics.drawable.bitmapdrawable#416e5 etc. Can anyone tell what the mistake is in my code, any help appreciated.
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
int sizeData = 0;
private View addButton;
protected Bitmap myBitmap;
private String image;
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
JSONArray jsonMainNode1 = jsonResponse.getJSONArray("menu");
// JSONObject e = jsonMainNode1.getJSONObject(position);
int lengthJsonArr = jsonMainNode1.length();
for(int i=0; i <lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode1.getJSONObject(i);
String Pid = jsonChildNode.optString("pid".toString());
String Name = jsonChildNode.optString("name").toString();
String Refid=jsonChildNode.optString("refid".toString());
String imagefile = jsonChildNode.getString("image_url");
String resName = imagefile.split("\\.")[2];
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);
OutputData = Name+image;
str_id = Pid;
LinearLayout buttonContainer=(LinearLayout)findViewById(R.id.btn_container);
Button button = new Button(buttonContainer.getContext());
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
ViewGroup.LayoutParams params = button.getLayoutParams();
//Button new width
params.width = 150;
params.height = 150;
button.setLayoutParams(params);
button.setText(OutputData);
// button.setBackground(itemImage);
button.setTag(Refid);
button.setTextColor(Color.parseColor("#FEFCFF"));
button.setBackgroundResource(R.drawable.button_color);
buttonContainer.addView(button);
Drawable image = getResources().getDrawable(resId);
You are trying to print the image which is a drawable object, So it will only display the address information as you see androidgraphics.drawable.bitmapdrawable#416e5
try
OutputData = Name;
you are setting background for button as
button.setBackgroundResource(R.drawable.button_color); are you sure that the image you expect is same as button_color, It sounds like a color.
you should do something as the following :
OutputData = Name;
then to add the text to the button do the following :
button.setText(OutputData);
and to add the image to the button do the following :
btn.setBackgroundResource(resId);
and give me some feedback
Hope that helps .