Converting ArrayList to JSONArray - android

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());
}

Related

I want to parse this json in Android but I'm getting repeated data

JSON:
{
"videos":[
[
{
"video_id":"DKOLynNhWxo",
"video_url":"https:\/\/www.youtube.com\/watch?v=DKOLynNhWxo",
"video_host":"youtube",
"created_at":"2017-08-08 11:17:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
},
{
"video_id":"haYm5k6h5yc",
"video_url":"https:\/\/www.youtube.com\/watch?v=haYm5k6h5yc",
"video_host":"Youtube",
"created_at":"2017-08-10 10:05:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
}
],
[
{
"video_id":"VSkRU8eXFII",
"video_url":"https:\/\/www.youtube.com\/watch?v=VSkRU8eXFII",
"video_host":"youtube",
"created_at":"2017-08-08 11:18:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"Maths"
}
],
[],
[]
]
}
Code:
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(JsonExp.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
AppController sh = new AppController();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("videos");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
//JSONObject cjsnobj = contacts.getJSONObject(i);
JSONArray c = contacts.getJSONArray(i);
for (int y = 0; y < c.length(); y++)
{
JSONObject obj=c.getJSONObject(i);
String aid = obj.getString("video_id");
String url = obj.getString("video_url");
// String name = obj.getString("video_host");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("video_id", aid);
contact.put("video_url", url);
// contact.put("video_host", name);
// adding contact to contact list
contactList.add(contact);
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
JsonExp.this, contactList,
R.layout.list_item, new String[]{"video_id","video_url"//, "video_host"//, "ProductDetails", "rectimestamp"
}, new int[]{R.id.aid, R.id.name
});
lv.setAdapter(adapter);
}
}
replace JSONObject obj=c.getJSONObject(i); with JSONObject obj=c.getJSONObject(y);
I strongly suggest you to use Gson
The example:
Create a model class
public class Video {
private String id;
private String url;
private String host;
private String date;
private String branch;
private String semester;
private String subject;
public Video(String id, String url, String host, String date, String branch, String semester, String subject) {
this.id = id;
this.url = url;
this.host = host;
this.date = date;
this.branch = branch;
this.semester = semester;
this.subject = subject;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public String getHost() {
return host;
}
public String getDate() {
return date;
}
public String getBranch() {
return branch;
}
public String getSemester() {
return semester;
}
public String getSubject() {
return subject;
}
}
Create an arraylist
JSONArray contacts = jsonObj.getJSONArray("videos");
ArrayList<Video> videos = new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
JSONObject contact = contacts.getJSONObject(i);
for (int y = 0; y < contact.length(); y++) {
JSONObject obj = contact.getJSONObject(y);
String id = obj.getString("video_id");
String url = obj.getString("video_url");
String host = obj.getString("video_host");
String date = obj.getString("created_at");
String branch = obj.getString("branch_name");
String semester = obj.getString("semester_name");
String subject = obj.getString("subject_name");
Video video = new Video(id, url, host, date, branch, semester, subject);
videos.add(video);
}
}
try{
JSONObject obj = nes JSONObject(yourResponse);
JSONArray video = obj.getJSONArray("videos");
for(i=0; i<video.length; i++){
JSONObject object = video.getJSONObject(i);
String subject_name = object.getString("subject_name");
}
}
catch(JSONException e){
}

Android: How to use extend ListActivity in extend Fragment

How to get the ListActivity properly into fragment? I always get an error.
I have this fragment:
public class Tools extends Fragment {
public Tools(){}
RelativeLayout view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.tools, container, false);
getActivity().setTitle("Tools");
return view;
}
}
and I want to use this Extend ListActivity in that fragment:
public class MainActivity extends ListActivity {
private String URL_ITEMS = "http://192.168.1.88/asd/getFixture.php";
private static final String TAG_FIXTURE = "fixture";
private static final String TAG_MATCHID = "matchId";
private static final String TAG_TEAMA = "teamA";
private static final String TAG_TEAMB = "teamB";
JSONArray matchFixture = null;
ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call Async task to get the match fixture
new GetFixture().execute();
}
private class GetFixture extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture response: ", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d("teamA", teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.matchId,R.id.teamA,
R.id.teamB
}
);
setListAdapter(adapter);
}
}
This is the code by which I tried to put that ListActivity into Fragment:
public class terbaru extends Fragment {
public terbaru(){}
RelativeLayout view;
private String URL_ITEMS = "http://192.168.1.88/asd/getFixture.php";
private static final String TAG_FIXTURE = "fixture";
private static final String TAG_MATCHID = "matchId";
private static final String TAG_TEAMA = "teamA";
private static final String TAG_TEAMB = "teamB";
JSONArray matchFixture = null;
ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.terbarus, container, false);
// Call Async task to get the match fixture
new GetFixture().execute();
}
private class GetFixture extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture response: ", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d("teamA", teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
terbaru.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.matchId,R.id.teamA,
R.id.teamB
}
);
setListAdapter(adapter);
return view;
}
}
You can not extend multiple class in java. To implement listview in Fragment you have to implement using Recyleview or listview manually or you can you extend ListFragment to implement ListActivity

Android data display in wrong format from JSONObject to ListView

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);
}
}

Android: Error parsing data and cannot be converted to JSONObject

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.

put function to display the loading process

I want to display the loading process when moving activity
This is my java file, where I have to put the function to process my application loading while loading data
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
}
AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
Try to use AsynchTask
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new task ().execute();
}
class task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDlg.setMessage("Loading...");
pDlg.setCancelable(false);
pDlg.setTitle(getResources().getString(R.string.app_name));
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected String doInBackground(String... params) {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDlg.dismiss();
this.adapter_listview();
}
}
Try to use AsyncTask for web service calls. Refer it fore more details developer.android.com/reference/android/os/AsyncTask.html
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new ServiceCallTask().execute();
this.adapter_listview();
}
class ServiceCallTask extends AsyncTask<String, String, String>
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(tehni.this, android.R.style.Theme_Translucent_NoTitleBar);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(progressDialog!=null)
progressDialog.dismiss();
this.adapter_listview();
}
}
}
Given that you will receive a NetworkOnMainTheadException if running a HTTP request on the UI thread, I will assume that your request is within jParser.AmbilJson().
So, the best approach is to use the methods of AsyncTask like onPreExecute and onPostExecute to display the result in a ProgressBar.

Categories

Resources