I am beginner in android how to pass this JSON http://coinabul.com/api.php and show the USD item of all catageory in a text box on main activity and when i m showing the log usd value is showing 210 for three keys but in json it have three different value
protected void onPostExecute(InputStream result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
String response = ConvertStreamIntoString.convertStreamToString(result);
Dictionary<String, Dictionary<String, String>> topDictionary = new Hashtable<String, Dictionary<String, String>>();
Dictionary<String, String> innerDictionary = new Hashtable<String, String>();
try {
JSONObject jsobject = new JSONObject(response);
Iterator<String> iterator = jsobject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
// String value = getString(jsobject, key);
String v2=null;
JSONObject jsonObject = jsobject.getJSONObject(key);
Iterator<String> iterator123 = jsonObject.keys();
while (iterator123.hasNext()) {
String keysss = (String) iterator123.next();
String value = getString(jsonObject, keysss);
innerDictionary.put(keysss, value);
Log.e("innerDict",innerDictionary.toString());
}
topDictionary.put(key, innerDictionary);
Log.e("asd", topDictionary.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.showdata(topDictionary, innerDictionary);
}
Please find the method below. You just need to pass the response string inside. Please let me know if you find any problem:
private void parseResponse(String response) throws JSONException {
Dictionary<String, Dictionary<String, String>> topDictionary = new Hashtable<String, Dictionary<String, String>>();
JSONObject jsobject = new JSONObject(response);
Iterator<String> iterator = jsobject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
JSONObject jsonObject = jsobject.getJSONObject(key);
Iterator<String> iterator123 = jsonObject.keys();
Dictionary<String, String> innerDictionary = new Hashtable<String, String>();
while (iterator123.hasNext()) {
String keysss = iterator123.next();
String value = jsonObject.getString(keysss);
innerDictionary.put(keysss, value);
}
topDictionary.put(key, innerDictionary);
}
Log.v("topDictionary",topDictionary.toString());
showdata(topDictionary);
}
private void showdata(
Dictionary<String, Dictionary<String, String>> topDictionary) {
for (Enumeration e = topDictionary.keys(); e.hasMoreElements();) {
String keyTop = e.nextElement().toString();
Log.v("keyTop",""+keyTop);
Dictionary<String, String> innerElements = topDictionary.get(keyTop);
for (Enumeration ei = innerElements.keys(); ei.hasMoreElements();) {
String keyInner = ei.nextElement().toString();
String value = innerElements.get(keyInner);
System.out.println("key: "+keyInner+" value:"+value);
// Here you can show your values in textview
}
}
}
Related
I have ArrayList with three values(Strings) but second is number and i want to sor numeric from 0 to e.g. 100. In this time it's sort 1,10,2,21,5 etc. In output i want to have 1,2,5,10,21.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray devices = jsonObj.getJSONArray("list");
for (int i = 0; i < devices.length(); i++) {
JSONObject c = devices.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String known = c.getString("known");
String description = c.getString("description");
String controllerId = c.getString("controllerId");
JSONObject frequencySurvey = c.getJSONObject("frequencySurvey");
if (frequencySurvey.has("5000")) {
JSONObject fivezero = frequencySurvey.getJSONObject("5000");
String timestamp = fivezero.getString("timestamp");
String clients = fivezero.getString("clients");
String enabled = fivezero.getString("enabled");
HashMap<String, String> device = new HashMap<>();
device.put("id", id);
device.put("name", name);
device.put("enabled", enabled);
device.put("clients", clients);
DevicesList.add(device);
}
ListAdapter adapter = new SimpleAdapter(Devices_5_0.this, DevicesList,
R.layout.list_item, new String[]{ "name","clients","enabled"},
new int[]{R.id.name,R.id.clients, enabled});
lv.setAdapter(adapter);
And I use this sort but it sort by strings:
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
return test1.get("clients").compareTo(test2.get("clients"));
}
}
You can convert a numeric string into integer
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
return new Integer(test1.get("clients"))
.compareTo(new Integer(test2.get("clients")));
}
}
If clients value is your number value this will work:
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
Long firstClients = Long.valueOf(test1.get("clients"));
Long secondClients = Long.valueOf(test2.get("clients"));
return firstClients.compareTo(secondClients);
}
}
try this:
Collections.sort(arrayList,new ArrayListHashMapComparator());
public class ArrayListHashMapComparator implements Comparator<HashMap<String,String>> {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
try {
return lhs.get(lhs.keySet()).compareToIgnoreCase(rhs.get(rhs.keySet()));
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
above code is sort all hashmap values in ascending order
You can try the following code for sorting arraylist values.
public ArrayList<NotificationValues> mAllNotificationList = new ArrayList<NotificationValues>();
Collections.sort(mAllNotificationList, new Comparator<NotificationValues>() {
#Override
public int compare(NotificationValues lhs, NotificationValues rhs) {
return lhs.getTimestamp().compareTo(rhs.getTimestamp());
}});
I've got a onClickListener which is sending data by json etc, but I want to after that, open new activity. Here is a part of code:
btnEnter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onLoginAttempt();
}
});
/*txtInvite.setText(Html.fromHtml(PreferenceConnector.readString(aiContext,
PreferenceConnector.INVITETEXT, "")));*/
HashMap<String, String> hash = new HashMap<String, String>();
hash.put("user_id", PreferenceConnector.readString(aiContext, PreferenceConnector.USERID,""));
hash.put("first_name", PreferenceConnector.readString(aiContext, PreferenceConnector.FIRST_NAME,""));
hash.put("last_name", PreferenceConnector.readString(aiContext, PreferenceConnector.LAST_NAME,""));
hash.put("email",PreferenceConnector.readString(aiContext, PreferenceConnector.PAYPAL_EMAIL,""));
hash.put("offer_id",getArguments().getString("offerid"));
//callWebService(GlobalVariables.REDEEM_OFFER, hash);
}
}
String strUserName, strPassword,strEmail;
private void onLoginAttempt() {
int response = 0;
response = gd.emptyEditTextError(
new EditText[]{first_nameEdit,last_nameEdit,email_editText},
new String[]{ getResources().getString(R.string.error_register_empty_first_name),
getResources().getString(R.string.error_register_empty_last_name),
getResources().getString(R.string.error_register_empty_email)
});
if (! GlobalData.isEmailValid(email_editText.getText().toString().trim())) {
response++;
email_editText.setError(getResources().getString(R.string.error_login_invalid_email));
}
if(response == 0) {
strUserName = first_nameEdit.getText().toString().trim();
strPassword = last_nameEdit.getText().toString().trim();
strEmail = email_editText.getText().toString().trim();
/*HashMap<String, String> hash = new HashMap<String, String>();
hash.put("user_id", PreferenceConnector.readString(aiContext, PreferenceConnector.USERID,""));
hash.put("first_name", PreferenceConnector.readString(aiContext, PreferenceConnector.FIRST_NAME,""));
hash.put("last_name", PreferenceConnector.readString(aiContext, PreferenceConnector.LAST_NAME,""));
hash.put("email",PreferenceConnector.readString(aiContext, PreferenceConnector.PAYPAL_EMAIL,""));
hash.put("offer_id",getArguments().getString("offerid"));*/
//callWebService(GlobalVariables.REDEEM_OFFER, hash);
String[] keys = {"user_id","first_name", "last_name", "email", "offer_id"};
String[] value = {PreferenceConnector.readString(aiContext, PreferenceConnector.USERID,""),strUserName, strPassword, strEmail,getArguments().getString("offerid")};
HashMap<String, String> hash = new HashMap<String, String>();
for (int i = 0; i < keys.length; i++) {
System.out.println(keys[i]+ "......." + value[i]);
hash.put(keys[i], value[i]);
}
if (gd.isConnectingToInternet()) {
callWebService(GlobalVariables.REDEEM_OFFER, hash);
}else {
GlobalData.showToast(getResources().getString(R.string.error_no_internet), aiContext);
}
}
}
private void callWebService(String postUrl, HashMap<String, String> hash) {
WebService webService = new WebService(aiContext, "", postUrl, hash, this, WebService.POST);
webService.execute();
}
#Override
public void onWebServiceActionComplete(String result, String url) {
System.out.println(result+".........jsonresponse....."+url);
try {
JSONObject json = new JSONObject(result);
String str_RESULT = json.getString(TAG_RESULT);
String str_Message = json.getString(TAG_MESSAGE);
if (str_RESULT.equals("YES")) {
GlobalData.showToast(getResources().getString(R.string.message_redeem_success), aiContext);
JSONObject Data_obj = json.getJSONObject(TAG_DATA);
String str_user_points = Data_obj.getString(DailyRewardFragment.TAG_USER_POINTS);
PreferenceConnector.writeInteger(aiContext, PreferenceConnector.WALLETPOINTS,
Integer.parseInt(str_user_points));
FragEarnCredits.onUpdateView(aiContext);
ViewRewardsFragment.onUpdateView(aiContext);
InviteFriendsFragment.onUpdateView(aiContext);
ConnectSocialFragment.onUpdateView(aiContext);
} else {
GlobalData.showToast(str_Message, aiContext);
}
} catch (JSONException e){
e.printStackTrace();
}
}
private void switchBack() {
if (getActivity() == null)
return;
if (getActivity() instanceof ActivityMainWallet) {
ActivityMainWallet mActivity = (ActivityMainWallet) getActivity();
mActivity.customizeActionBar();
mActivity.switchBack();
}
Intent i = new Intent(getApplicationContext(),Zamawiam.class);
startActivity(i);
}
}
The new activity I want to open I implemented with:
Intent i = new Intent(getApplicationContext(),Zamawiam.class);
startActivity(i);
Where is a problem? Data is sent, I'm getting success toast and nothing.
From the code you pasted it seems like you're not calling the switchBack() method which is where you start your activity, unless it's called elsewhere.
You can check by setting a breakpoint and debug the app. Here's how https://developer.android.com/studio/debug/index.html#breakPoints
I try to display 2 column data with HashMap and Listview, it works fine. The error comes when I try to display more than 2 columns.
2_columns.java
public class Main4Activity extends AppCompatActivity {
String url = "http://192.168.1.103/web_service/omg.php/";
private static final String COLUMN_ID = "ID";
private static final String COLUMN_NAME = "Name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
try {
Iterator<String> iterator = response.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String value = response.getString(key);
HashMap<String, String> map = new HashMap<>();
map.put(COLUMN_ID, key);
map.put(COLUMN_NAME, value);
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
if(aList.size() > 0) {
String[] from = {COLUMN_ID, COLUMN_NAME};
int[] to = {R.id.text_id, R.id.text_name};
SimpleAdapter adapter = new SimpleAdapter(Main4Activity.this, aList, R.layout.list_item, from, to);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", "error ");
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);
}
}
localhost/web_service/omg.php
{
"32":"Western Food",
"33":"Chinese Food",
"34":"Mix Food",
"35":"Japanese Food",
"36":"Korean Food",
"37":"Italian Food",
"38":"German Food"
}
The above coding is working fine. But the errors come when I try to display data in multiple columns,
multiple_columns.java
String url = "http://192.168.1.103/web_service/ohno.php/";
private static final String product_sku = "SKU";
private static final String product_name = "Name";
private static final String product_price = "Price";
private static final String product_quantity = "Quantity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
try {
Iterator<String> iterator = response.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String value_sku = response.getString(key);
String value_name= response.getString(key);
String value_price= response.getString(key);
String value_quantity= response.getString(key);
HashMap<String, String> map = new HashMap<>();
map.put(product_sku, value_sku);
map.put(product_name, value_name);
map.put(product_price, value_price);
map.put(product_quantity, value_quantity);
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
if(aList.size() > 0) {
String[] from = {product_sku,product_name, product_price,product_quantity};
int[] to = {R.id.sku,R.id.name, R.id.price,R.id.quantity};
SimpleAdapter adapter = new SimpleAdapter(Main5Activity.this, aList, R.layout.list_item2, from, to);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", "error ");
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);
}
localhost/web_service/ohno.php
{
"482":["1","Chicken Rice","1","1"],
"483":["1","French Fries","1","1"],
"484":["1","apple","1","1"],
"492":["1","western+italian","1","1"],
"493":["1","no_cat","1","1"]
}
As you can see from the above screenshot, I want the Key to be 482,483,484... and the value its on the right side. What's wrong with the coding?
Seems like the values in your JSON are JSONArrays, so response.getString(key) will return the whole array as a String.
Call getJSONArray() to get the values as a JSONArray, so you can process the items individually.
Something like this should work:
try {
Iterator<String> iterator = response.keys();
while (iterator.hasNext()) {
String key = iterator.next();
JSONArray array = response.getJSONArray(key);
HashMap<String, String> map = new HashMap<>();
map.put(product_sku, array.getString(0));
map.put(product_name, array.getString(1));
map.put(product_price, array.getString(2));
map.put(product_quantity, array.getString(3));
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
You are parsing JSONArray as using JSONObject which is wrong. So Try as follows
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
try {
Iterator<String> iterator = response.keys();
while (iterator.hasNext()) {
String key = iterator.next();
JSONArray jsonArray = response.getJSONArray(key);
String value_sku = jsonArray.get(0).toString();
String value_name = jsonArray.get(1).toString();
String value_price = jsonArray.get(2).toString();
String value_quantity = jsonArray.get(3).toString();
HashMap<String, String> map = new HashMap<>();
map.put(product_sku, value_sku);
map.put(product_name, value_name);
map.put(product_price, value_price);
map.put(product_quantity, value_quantity);
aList.add(map);
}
}
I am using ArrayList<HashMap<String,String>> to store my cart items. But I need to convert it to JSONArray to send it to the database. But when I convert it to JSONArray the JSONArray looks like this:
03-13 11:09:28.842: D/cart before(1339): [{image=2130837526,
category=Chairs, Quantity=1, price=400, name=chair, prodId=34},
{image=2130837566, category=Mirrors, Quantity=1, price=3000, name=La
Fonda, prodId=35}]
03-13 11:09:28.842: D/cart after converting into JSONArray(1339):
["{image=2130837526, category=Chairs, Quantity=1, price=400,
name=chair, prodId=34}","{image=2130837566, category=Mirrors,
Quantity=1, price=3000, name=La Fonda, prodId=35}"]
Which I believe is wrong. Instead it should be converted to something like this:
cartitems=[{"name":"Chair","price":"1001","prodId":"2","category":"Chairs","image":"2130837519","Quantity":"1"},{"name":"Baxton Studio Club Chair","price":"4545","prodId":"5","category":"Chairs","image":"2130837521","Quantity":"1"}]
Code to convert to JSONArray:
protected String doInBackground(String... args) {
AddtoCart obj = (AddtoCart) getApplicationContext();
JSONArray cart = new JSONArray(obj.getCart());
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("email", email);
params.put("payment", payment);
params.put("address", useraddress);
params.put("contact", contact);
params.put("city", usercity);
params.put("cartitems", cart.toString());
Log.d("params", params.toString());
JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params);
try {
success = json.getInt("success");
message = json.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Class holding ArrayList:
public class AddtoCart extends Application {
private static final String TAG_QUANTITY = "Quantity";
private static final String TAG_PRICE = "price";
ArrayList<HashMap<String, String>> cart = new ArrayList<HashMap<String, String>>();
public void setCart(ArrayList<HashMap<String, String>> data) {
//cart = data;
cart.addAll(data);
Log.d("Items in the cart", String.valueOf(cart));
}
public ArrayList<HashMap<String, String>> getCart() {
return cart;
}
public int getSize() {
return cart.size();
}
public void updateCart(ArrayList<HashMap<String, String>> data) {
cart = data;
Log.d("UPDATED CART", String.valueOf(cart));
}
public void updateQuantity(int index, String quantity) {
cart.get(index).put(TAG_QUANTITY,quantity);
}
}
I found this to be helpful in my project:
Object in my ArrayList<>
public class ListItem {
private long _masterId;
private String _name;
private long _category;
public ListItem(long masterId, String name, long category) {
_masterId = masterId;
_name = name;
_category = category;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Id", _masterId);
obj.put("Name", _name);
obj.put("Category", _category);
} catch (JSONException e) {
trace("DefaultListItem.toString JSONException: "+e.getMessage());
}
return obj;
}
}
The actual conversion:
ArrayList<ListItem> myCustomList = ArrayList<ListItem>();
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
jsonArray.put(myCustomList.get(i).getJSONObject());
}
I'm trying to send the user_id to PHP through JSON but it shows Error parsing data org.json.JSONException: Value 2 of type java.lang.Integer cannot be converted to JSONObject.
How can i make this work? Thank you in advance.
Class :
public class Home1 extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter1 adapterrr;
SharedPreferences pref;
String uid;
String user_i,us;
String ques_i;
ArrayList<HashMap<String, String>> arraylist;
//static String BET_ID = "bet_id";
static String QUESTION = "question";
static String QUES_ID = "ques_id";
static String ANSWER = "answer";
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
Set<String> newset=new HashSet<String>();
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.questionlist1);
uid = pref.getString("user_id",null);
Log.d("uid", ""+uid);
Intent i = getIntent();
ques_i = i.getStringExtra("qsid");
Log.d("qsid", ""+ques_i);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
/*protected ArrayList<NameValuePair> parameters;
public DownloadJSON() {
parameters = new ArrayList<NameValuePair>();
NameValuePair us = new BasicNameValuePair("user_id", uid);
parameters.add(us);
}*/
#Override
protected Void doInBackground(Void... params) {
arraylist = new ArrayList<HashMap<String, String>>();
/*jsonobject = JSONfunctions
.getJSONfromURL("http://192.168.1.23/mutilatedphp/QuizGame/filtercheck.php");*/
try {
jsonobject = JSONfunctions
.getJSONfromURL("http://192.168.1.23/mutilatedphp/QuizGame/filtercheck.php?user_id="+uid);
jsonarray = jsonobject.getJSONArray("ques");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("ques_id", jsonobject.getString("ques_id"));
map.put("question", jsonobject.getString("question"));
map.put("answer", jsonobject.getString("answer"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listView2);
adapterrr = new ListViewAdapter1(Home1.this, arraylist);
listview.setAdapter(adapterrr);
}
The problem is caused by this line
jsonobject = jsonarray.getJSONObject(i);
You are trying to convert an object of type Integer into a JSONObject. The problem is on the server side. Please post your response, if you found the problem, so I can verify if I'm right here.
I think the problem is that you haven't check whether the attribute 'ques' exists.
When you use getJSONArray() method on an non-exist attribute, JSON library will throw a exception and crash your app.
You can take a look at my little example, it checks the existence of 'ques' before doing anything further:
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class SimpleTest {
public static void main(String[] args) {
String notOk = "{\n" +
"\t\"success\":0,\n" +
"\t\"message\":\"No Categories found\"\n" +
"}";
String ok = "{\n" +
"\t\"ques\":\n" +
"\t\t[\n" +
"\t\t\t{\n" +
"\t\t\t\t\"ques_id\":\"3\",\n" +
"\t\t\t\t\"question\":\"What is the currency of Japan?\",\n" +
"\t\t\t\t\"answer\":\"Yen\"\n" +
"\t\t\t}\n" +
"\t\t],\n" +
"\t\"success\":1,\n" +
"\t\"message\":\"Successfully found \"\n" +
"}";
JSONObject okJSON = new JSONObject(ok);
JSONObject notOkJSON = new JSONObject(notOk);
System.out.println(new SimpleTest().parseJson(okJSON));
System.out.println(new SimpleTest().parseJson(notOkJSON));
}
public Map<String, String> parseJson(JSONObject jsonObject) {
if (jsonObject.has("ques")) {
JSONArray jsonArray = jsonObject.getJSONArray("ques");
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject tempObject = jsonArray.getJSONObject(i);
map.put("ques_id", tempObject.getString("ques_id"));
map.put("question", tempObject.getString("question"));
map.put("answer", tempObject.getString("answer"));
}
return map;
} else {
return new HashMap<String, String>();
}
}
}
Or, it is totally ok to use the 'success' attribute to check the result and tell you whether 'ques' attribute exists.
Hope my answer can give you a little help.