Android: Error parsing data and cannot be converted to JSONObject - android

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.

Related

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

Converting ArrayList to JSONArray

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

Unable to parse the JSON

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

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.

AsyncTas Implementation ListView

How to use asynctask to show listview from json
how to put
onPreExecute()
onPostExecute()
doInBackground()
onProgressUpdate()
MainActivity.java
list = (ListView) activity.findViewById(R.id.listView1);
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for(int i = 0; i < following.length(); i++){
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing xml data ArrayList
adapter1=new LazyAdapter(this, followingList);
list.setAdapter(adapter1);
How to implementation asycntask to show list view?
DashboardTask
package net.drieanto.lagidimana;
import net.drieanto.lagidimana.library.DatabaseHandler;
import net.drieanto.lagidimana.library.JSONParser;
import net.drieanto.lagidimana.library.UserFunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class DashboardTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private DashboardActivity activity;
ListView list1;
LazyAdapter adapter1;
private ListView list;
// All static variables
static final String URL = "http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/XX3";
// JSON node keys
private int responseCode = 0;
static final String KEY_FOLLOWING = "following";
static final String KEY_NAMA = "nama"; // parent node
static final String KEY_INSTANSI = "instansi";
static final String KEY_STATUS = "status";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
// following JSONArray
JSONArray following = null;
public DashboardTask(DashboardActivity activity,
ProgressDialog progressDialog) {
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
responseCode = 1;
} else {
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
progressDialog.dismiss();
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for (int i = 0; i < following.length(); i++) {
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing xml data ArrayList
adapter1 = new LazyAdapter(activity, followingList);
list.setAdapter(adapter1);
} else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
}
But contain error whats wrong?
You can use the following
ProgressDialog pd;
LazyAdapter adapter1;
ListView list;
String URL;
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
In your activity onCreate()
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
pd = new ProgressDialog(ActivityName.this);
pd.setTitle("Processing...");
URL ="your url";
new TheTask().execute();
Define Asynctask as a inner class in your activity class
class extends AsyncTask<Void,Void,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for(int i = 0; i < following.length(); i++){
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS)
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
adapter1=new LazyAdapter(ActivityName.this, followingList);
list.setAdapter(adapter1);
}
}
Exaplanation
AsyncTask is invoked on the UI thread.
onPreExecute() invoked on UI Thread. display progress dialog
doInBackground() invoked on the background thread. do some operation. Do not update UI here
OnPostExecute() invoked on UI thread. dismiss dialog and update ui here.
For more info check the doc
http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources