Trying to get a single json object android - android

Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONObject ja= new JSONObject(jsonData);
persons.clear();
Person s=null;
JSONObject jo=ja.getJSONObject("full_name");
if (jo.equals("John")) {
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working

I'm going to guess that you have a JSONArray of person and you want to get the object that has person = John.
If the data is like this
[{
"full_name": "John Smith",
"sex": "male",
"location": "New York, NY, United States"
}, {
"full_name": "Angela Johnson",
"sex": "female",
"location": "San Diego, CA, United States"
}]
You can write:
JSONArray people = new JSONArray(jsondata);
int index = 0;
for (int i = 0; i < people.length(); i++) {
JSONObject tmpObj = people.getJSONObject(i);
string name = tmpObj.getString("full_name");
if (name == "John") {
index = i;
break;
}
}
JSONObject johnObjExample = people.getJSONObject(index);
string johnName = johnObjExample.getString("full_name");
int id = johnObjExample.getInt("id");
String name = johnObjExample.getString("full_name");
String sex = johnObjExample.getString("sex");
String location = johnObjExample.getString("location");

Related

How to fetch a data from the database mysql using asynctask?

While fetching data in TextView I am getting an error. I tried but its not working.
Error parsing data org.json.JSONException: End of input at character 0
Json
[{
"0": "1",
"cl_id": "1",
"1": "",
"cl_department": "",
"2": "3G COMMUNICATION",
"cl_pname": "3G COMMUNICATION",
"3": "NIRAJBHAI",
"cl_salesperson": "NIRAJBHAI",
"4": "",
"cl_oname": "",
"5": "MOHMADBHAI",
"cl_contact": "MOHMADBHAI",
"6": "JUBELY SHAK MARKET",
"cl_address": "JUBELY SHAK MARKET",
"7": "",
"cl_city": "",
"8": "360001",
"cl_pincode": "360001",
"9": "",
"cl_bdate": "",
"10": "",
"cl_adate": "",
"11": "",
"cl_opening": "",
"12": "9376052000",
"cl_cnumber": "9376052000",
"13": "",
"cl_wnumber": "",
"14": "",
"cl_email": "",
"15": "RT40848",
"cl_wodcode": "RT40848",
"16": "",
"cl_active": "",
"17": "",
"cl_saleman": "",
"18": "",
"cl_bank_name": "",
"19": "",
"cl_bank_city": "",
"20": "",
"cl_ifsc_code": "",
"21": "",
"cl_bank_ac_no": "",
"22": "",
"cl_bank_ac_holder": "",
"23": "",
"cl_pancard_no": "",
"24": "",
"cl_visiting_card": "",
"25": "ACTIVE",
"cl_status": "ACTIVE",
"26": "",
"cl_aread": "",
"27": "",
"cl_target": "",
"28": "",
"cl_archive": "",
"29": "",
"cl_remaining": "",
"30": "A1",
"cl_group": "A1",
"31": "Om",
"cl_category": "Om",
"32": "",
"cl_credit": ""
},
Here is my complete code,
Main.java
public class MainActivity extends Activity {
private WebView wv1;
InputStream is=null;
String result=null;
String line=null;
JSONObject jsonobject;
public static String DATA_URL = "http://10.0.2.2/portal/fetchwod.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
String suid,uid,wt_wod_code1,wt_party1;
TextView abcd,abc1;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
abcd =(TextView)findViewById(R.id.abc);
abc1 =(TextView)findViewById(R.id.abc1);
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url ) {
view.loadUrl(url);
String id = abcd.getText().toString().trim();
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/autocomplete.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
JSONArray JA = new JSONArray(result);
JSONObject json = null;
final String[] str1 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
}
final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final List<String> list = new ArrayList<String>();
for (int i = 0; i < str1.length; i++) {
list.add(str1[i]);
}
Collections.sort(list);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.my_list_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
text.setThreshold(1);
text.setAdapter(dataAdapter);
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
wv1 = (WebView) findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
wv1.loadUrl("http://10.0.2.2/portal/on_target.php?=cod");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Toast.makeText(getApplicationContext(), (CharSequence) arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
wt_wod_code1 = text.getText().toString();
wt_party1 = text.getText().toString();
abcd.setText(text.getText());
Log.d("wt_wod_code", wt_party1);
new getdata().execute();
}
});
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
private class getdata extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
String uid = abcd.getText().toString().trim();
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cl_pname", uid));
JSONObject json = jParser.makeHttpRequest(DATA_URL, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
ownerObj = json.getJSONArray("Ordera");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
delivery_fetch.add(jsonobject.getString("cl_wodcode"));
}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void args) {
abc1 =(TextView)findViewById(R.id.abc1);
abc1.setText(delivery_fetch.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Here is my Logcat,
com.example.sachin.addvisit E/Pass 1: connection success
com.example.sachin.addvisit E/Pass 2: connection success
com.example.sachin.addvisit D/wt_wod_code: D.K. METAL
com.example.sachin.addvisit D/response: {"success":1,"Ordera":[{"cl_wodcode":"RT34705","cl_pname":"D.K. METAL"}]}
com.example.sachin.addvisit E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.sachin.addvisit E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
The data is displaying in the logcat but not fetching in the TextView.
I validated my JSON online an it looks alright.
i don't know where's the problem is please help me out.
if required i'll post my API too..
Parse the JSON as follows,
final String[] str1 = new String[JA.length()];
final String[] str2 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
str2[i] = json.getString("cl_wodcode");
}
Inside the OnItemClickListener,
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected_cl_pname = (String) parent.getItemAtPosition(position);
int index = Arrays.asList(str1).indexOf(selected_cl_pname);
String selected_cl_wodcode = str2[index];
abc1.setText(selected_cl_wodcode);
// rest of your code
}
});
I recommend to use a model class and use GSON to parse the JSON.

Android, random from external json

I am working on an android app. I want the app to select randomly a name from json.
Here is the json :
{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw#gmail.com"
},
{
"id": "002",
"name": "Raj",
"email": "amalw#gmail.com"
}
]
}
And here is my android code :
public class MainActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://weblink/json/index.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
I would that when I presse the button a random name shows and loops.
Please help
Thank you
Change JSONObject c = user.getJSONObject(0); by this line ->
JSONObject c = user.getJSONObject(new Random().nextInt(user.length()));
you need to generate Random number from your array
first try this to add items in temp Arraylist. i am just only adding characters you need to replace name instead of characters
String json="{'abridged_cast':
[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},
{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},
{'name':'JessicaLange','id':'162653068','characters':['Dwan']},
{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},
{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast"); // add
//user here instead of abridged_cas
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters"); // replace
//name instead of characters
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here is you get names randomly using onclick or whatever you want.
Random randomizer = new Random();
String RandomName = temp.get(randomizer.nextInt(temp.size()));
Loop through the JSON input. You can use java function int random = Random.nextInt(n). This returns a random int in range[0, n-1].
ArrayList<String> names = new ArrayList<>();
JSONArray socialArray = response.getJSONArray(data);
for (int i = 0; i < socialArray.length(); i++) {
JSONObject currentJSON = socialArray.getJSONObject(i);
names.add(currentJSON.getString("name");
}
final int random = Random.nextInt(names.size() + 1);
Toast.makeText(this, "Random Name: " + names.get(random), LENGTH.SHORT).show();

Android List with Search not working

Problem is with the filter(Textwatcher) : My app, show 2 record when data matches the value present in the first name & 1 record when the record matches the value in lastname.
example: when I type M it will show 2 record for mary but when I type k it show 1 record of mary kom and 2 record of Karl plus json data(refer below json)
{
"details": [
{
"id": "01",
"name": "Mary Kom",
"email": "abc#uvw.in",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "02",
"name": "karl plus",
"email": "pqrp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]}
Code:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
EditText inputSearch;
ListAdapter adapter;
// URL to get contacts JSON
private static String url = "http://www.abcd.in/api/details";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Enabling Search Filter
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
// When user change the Text
((SimpleAdapter) adapter).getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable cs) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// 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 email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
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_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// 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
* */
adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]
{ TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] { R.id.name,R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I think it is a default behavior of filter with SimpleAdapter. what you wants to achieve, you need to implement your own custom filter.
See the Example here :- http://www.androidbegin.com/tutorial/android-search-listview-using-filter/
Change this code :
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
to
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).startsWith(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
It help you to achieve functionality.

Android: Best practice for handling JSON data

I've been researching how to query JSON data from a server and parse it for use in my application. However, I've found a number of different ways to do the same thing. I realize there are different JSON parsers out there, so let's assume I'm sticking with the standard one. The main question I have has to do with the server requests. Here is my current code for my MapActivity
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a Progress Dialog
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Retrieve JSON Objects from the given URL address
jsonarray = JSONFunctions.getJSONfromURL("myurl");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("id", String.valueOf(i));
map.put("name", obj.getString("name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Do something with data
mProgressDialog.dismiss();
}
}
If the structure of my JSON data looks weird, it's because it's stored in an unnamed array so I don't have to create an object first. Anyway... I essentially based this off of this tutorial. However, they have soooo much more code. Is that all really necessary? I didn't think so. I searched around more and found other examples that used half the code and essentially did the same thing. So my question, as a beginning Android programmer, is what is the best practice for handling JSON data? Thanks!
Example of JSON file:
[
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
},
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
}
]
Try this...
private class TestJSONParsing extends AsyncTask<JSONArray, Void, JSONArray>
{
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> map;
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected JSONArray doInBackground(JSONArray... params)
{
return JSONFunctions.getJSONfromURL("myurl");
}
#Override
protected void onPostExecute(JSONArray resultArray)
{
super.onPostExecute(resultArray);
mProgressDialog.dismiss();
if (null != resultArray)
{
int resultLength = resultArray.length();
if (resultLength > 0)
{
try
{
for (int i = 0; i < resultLength; i++)
{
JSONObject jsonObject = resultArray
.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", jsonObject.getString("name"));
arraylist.add(map);
}
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
if (arraylist.size() > 0)
{
SimpleAdapter adapter = new SimpleAdapter(
MapActivity.this, arraylist,
R.layout.your_simple_row, new String[]
{ "id", "name" }, new int[]
{ R.id.nameId, R.id.name });
// bind adapter to your components
listView.setAdapter(adapter);
}
}
} else
{
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
}
}
#leerob Hello, at one time I found myself in a dilemma where you are, but lately I have used base classes that brings Android to handle json and is pretty good, a good practice I recommend you is to declare constants for the keys of json, I share an example:
public void insertMovieTypeFromJson(String movieTypeJsonStr) throws JSONException {
final String ID = "id";
final String TYPE = "type";
final String DESCRIPTION = "description";
if (movieTypeJsonStr == null)
return;
try {
JSONArray movieTypeArrayJson = new JSONArray(movieTypeJsonStr);
Vector<ContentValues> cVVector = new Vector<>(movieTypeArrayJson.length());
for (int i = 0; i < movieTypeArrayJson.length(); i++) {
long id;
String type;
String description;
JSONObject movie = movieTypeArrayJson.getJSONObject(i);
id = movie.getLong(ID);
type = movie.getString(TYPE);
description = movie.getString(DESCRIPTION);
ContentValues movieTypeValues = new ContentValues();
movieTypeValues.put(MovieContract.MovieTypeEntry._ID, id);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_TYPE, type);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_DESCRIPTION, description);
cVVector.add(movieTypeValues);
}
int inserted = 0;
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = getContext().getContentResolver().bulkInsert(MovieContract.MovieTypeEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "MovieTask Complete. " + inserted + " MovieType Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
Json:
[
{
"id": "1",
"type": "Action & Adventure",
"description": "Action & Adventure"
},
{
"id": "2",
"type": "Animation",
"description": "Animation"
},
{
"id": "3",
"type": "Comedy",
"description": "Comedy"
},
{
"id": "4",
"type": "Terror",
"description": "Terror"
}
]

Retrieve json data

I am working on an app which I need to parse jsonarray. I have my json values in base64 and I need to decode strings to retrive data with decode String. Here is my code :
private class DecodeData extends AsyncTask<String, Void, String> {
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String response = params[0];
String keys = "";
String value = "";
String b64Value = "";
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String)it.next();
value = (String)array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map.toString();
}
I get only the first JSONObject and I need to get all JSONObject with all values. I can't use getString(name) because my json can have others keys. What am I doing wrong and why am I getting only the first JSONObject and not the others ?
json type :
[
{
"value": "ZG1WdVpISmxaR2tnTWpVZ1lYWnlhV3c4WW5JZ0x6NEtSMVZaUVU1QklFRk1UQ0JUVkVGUw==",
"date_create": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNWF2cmlsLmpwZw==",
"link": "",
"title": "MjVhdnJpbA==",
"media": "",
"id_news": "MTA5NjI0",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "dmVuZHJlZGkgMjUgYXZyaWxHVVlBTkEgQUxMIFNUQVI="
},
{
"value": "YzJGdFpXUnBJREkySUdGMmNtbHNQR0p5SUM4K0NrMUJVbFpKVGlCaGJtUWdSbEpKUlU1RVV3PT0=",
"date_create": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNmF2cmlsMi5qcGc=",
"link": "",
"title": "MjZhdnJpbA==",
"media": "",
"id_news": "MTA5NjMx",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "c2FtZWRpIDI2IGF2cmlsTUFSVklOIGFuZCBGUklFTkRT"
},
Here is what i am getting with my code :
RESPONSE :{date_create=MjAxNC0wNS0yNSAwMDowMDowMA==, link=, date_event=MjAxNC0wNS0yNSAwMDowMDowMA==, type=, value_out=ZGltYW5jaGUgMjUgbWFpRE9MQSBNSVpJSyBlbiBjb25jZXJ0, picture=aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNW1haS5qcGc=, title=MjUgbWFp, id_reference=, chapo=, value=WkdsdFlXNWphR1VnTWpVZ2JXRnBQR0p5SUM4K0NqeGljaUF2UGdwRVQweEJJRTFKV2tsTElHVnVJR052Ym1ObGNuUT0=, id_news=MTA5NjM0, media=, auteur=, id_categorie=}
Anybody has an idea of how I can do ?
Thank you
Problem:
You are putting all results in the same Map. Each object in the JSONArray will erase the values of previous objects because the keys are the same.
In the end, you get only one value for each key.
Solution:
You need one map per JSON object in the array. You could use a list (or array) of Maps, for instance. Here is some code:
ArrayList<HashMap<String, String>> decodedArray = new ArrayList<>();
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<>();
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String) it.next();
value = (String) array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
decodedArray.add(map);
}
Add you json value into model object I hope it would be helpful for you.
public class A {
private Vector<B> b = new Vector<B>();
public Vector<B> getB() {
return b;
}
public void addB(B b) {
this.b.add(b);
}
public class B{
private String value;
private String picture;
//add your paramatere here like link, title etc
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
}
Then after parsing value set into bean object like that.
A a = new A();
for (int i = 0; i < jsonArray.length(); i++) {
B b= a.new B();
JSONObject jsonObject= (JSONObject)jsonArray.get(i);
String value= jsonObject.getString("value");
jsonObject.getString("picture");
// get all value from json object set into b object
a.addB(b);
}

Categories

Resources