Base Adapter in Asynctask not working - java

I am working with facebook app for my project and I'm getting a json from the graph API. I have a custom listView with hashMap, but when I run, the list wont populate but there isn't any errors. please help me.
here are the codes:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
}
}

Move this code :
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv }); //initialize adapter
listView.setAdapter(adapter); //set adapter
adapter.notifyDataSetChanged();
To the AsyncTask's onPostExecute to make sure the feedList is already inserted from the onBackground.
Or if you prefer to initialize your adapter and setting the adapter to the listview in the onCreate, just move adapter.notifyDataSetChanged(); to the onPostExecute. This is recommended if you call the AsyncTask multiple times, because theres no need to initialize and set the adapter multiple times. (see my comment in the code)

ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
}

Related

NPE during creating an array from MySQL

I want to create the multiple array of data from MySQL, but received NullPointerException. The error is found here: JSONObject jsonResponse = new JSONObject...
NewsFeed.java
public class NewsFeed extends Fragment {
public NewsFeed() {
// Required empty public constructor
}
String T = "check";
TextView newsTime;
TextView newsTitle;
TextView newsSection;
//TextView txtT;
//String title2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rv = inflater.inflate(R.layout.newsfeed, container, false);
LayoutInflater infnews = getLayoutInflater();
LinearLayout linearLayout =
(LinearLayout)rv.findViewById(R.id.linear_newsfeed);
final View view1 = infnews.inflate(R.layout.newsfront, linearLayout,
false);
view1.getLayoutParams().width =
RelativeLayout.LayoutParams.MATCH_PARENT;
linearLayout.addView(view1);
newsTime = (TextView)rv.findViewById(R.id.newsTime);
newsTitle = (TextView)rv.findViewById(R.id.newsTitle);
newsSection = (TextView)rv.findViewById(R.id.newsSection);
Typeface GothamProFont =
Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamPro.ttf");
newsTime.setTypeface(GothamProFont);
newsTitle.setTypeface(GothamProFont);
newsSection.setTypeface(GothamProFont);
newsFeedDisplay();
view1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewsBody.class);
startActivity(intent);
}
});
return rv;
}
void newsFeedDisplay () {
Response.Listener<String> responseListener = new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new
JSONObject(jsonResult.substring(jsonResult.indexOf("{"),
jsonResult.lastIndexOf("}")+1));
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
final ArrayList<HashMap<String,String>> MyArrList = new
ArrayList<HashMap<String, String>>();
HashMap<String,String> map;
for(int i=0; i<jsonMainNode.length(); i++){
JSONObject c = jsonMainNode.getJSONObject(i);
Log.i(T, c.toString());
map = new HashMap<String,String>();
map.put("title", c.getString("title"));
map.put("time", c.getString("time"));
map.put("section", c.getString("section"));
MyArrList.add(map);
Log.i(T, MyArrList.toString());
SimpleAdapter sAdap;
//sAdap = new SimpleAdapter(getActivity(), MyArrList,
R.layout.activity_column, new String[]{"MemberID","Name","city"}, new int[]
{R.id.ColMemberID, R.id.ColName, R.id.Colcity});
//listView.setAdapter(sAdap);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
NewsFeedRequest3 newsFeedRequest3 = new
NewsFeedRequest3(responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(newsFeedRequest3);
}
}
NewsFeedRequest3
public class NewsFeedRequest3 extends StringRequest{
private static final String REGISTER_REQUEST_URL =
"https://blazhko.000webhostapp.com/test.php";
private Map<String, String> params;
public NewsFeedRequest3(Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
//params.put("section", section);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference
at blazhko.sportarena.main_screen.NewsFeed$3.onResponse(NewsFeed.java:145)
at blazhko.sportarena.main_screen.NewsFeed$3.onResponse(NewsFeed.java:141)
What I do incorrectly? Please help me.
According to your problem
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference at
You can do like this .
1.Do you get the correct response in your code? jsonResult or response .
2.Deal with NullPointerException
3.make sure that your code contain { and }.
You can do this . If you use jsonResult as result , you can change to jsonResult in your code .
#Override
public void onResponse(String response) {
// String response = "hello{\"key\":\"value\"}world"; if you response like this
try {
if (response != null) {
JSONObject jsonResponse = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
// do something here
Log.e("TAG", response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
}
} catch (Exception e) {
e.printStackTrace();
}
}

Getting JSON.typeMismatch error

Everytime I run my code I get the following error.
JSON.typeMismatch(JSON.java:111)
How can I parse a JSONObject wrapped with an array?
Here is my code.
public class FeedActivity extends AppCompatActivity implements OnFeedListener {
ListView listView;
FeedAdapter adapter;
ArrayList<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
listView = (ListView)findViewById(R.id.listView);
adapter = new FeedAdapter(getApplicationContext(), R.layout.layout_feed_item);
listView.setAdapter(adapter);
FeedTask task= new FeedTask(this);
task.execute("http://www.botswanayouth.com/wp-json/wp/v2/posts");
}
#Override
public void onFeed(JSONArray array) {
posts= new ArrayList<>();
int length = array.length();
for (int i = 0; i < length; ++i) {
JSONObject object = array.optJSONObject(i);
Post post = new Post(object.optString("title"),object.optString("excerpt"),object.optString("featured_media"));
posts.add(post);
}
adapter.addAll(posts);
}
public class FeedTask extends AsyncTask<String, Void, JSONArray> {
private OnFeedListener listener;
public FeedTask(OnFeedListener listener) {
this.listener= listener;
}
#Override
protected JSONArray doInBackground(String... params) {
String url = params[0];
OkHttpClient client= new OkHttpClient();
Request.Builder builder= new Request.Builder();
Request request= builder.url(url).build();
try {
Response response= client.newCall(request).execute();
String json= response.body().string();
try {
JSONObject object= new JSONObject(json);
JSONArray array = object.optJSONArray("posts");
return array;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
if (null== array)
return;
if (null != listener)
listener.onFeed(array);
}
}
public class FeedAdapter extends ArrayAdapter<Post> {
private int resource;
public FeedAdapter(Context context, int resource) {
super(context, resource);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null==convertView) {
LayoutInflater inflater=LayoutInflater.from(getContext());
convertView=inflater.inflate(resource, null);
}
Post post = getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView desc = (TextView) convertView.findViewById(R.id.description);
title.setText(post.title);
desc.setText(post.description);
return convertView;
}
}
public class Post {
public String title;
public String description;
public String thumbnail; //URL
public Post(String title, String desc, String thumbnail) {
this.title=title;
this.description=desc;
this.thumbnail=thumbnail;
}
}
}
If this is your json
array-[
0object-{ "id" : number5878, "date" : string2016-09-20T14:04:01, "guid" :
object-{ "rendered" : stringhttp:\/\/botswanayouth.com\/?p=5877 },
"type" : stringpost, "link" : stringhttp:\/\/botswanayouth.com\/5877\/blow-blow-rappers-be‌​ef-dramaboi-vs-emtee‌​\/,
"title" : object+{ ... }, "content" : object+{ ... }, "excerpt" :
object-{ "rendered" : string<p> Sessions next month at Stanbic Bank.<\/p>}
]
Then in your initial response you are getting a json array not a json object.
So this
String json= response.body().string();
try {
JSONObject object= new JSONObject(json);
....
}
Should be
String json= response.body().string();
try {
JSONArray object= new JSONArray(json);
....
}
But it's honestly a little hard to tell because what you've provided doesn't match your code. For example you are looking for a "posts" array in your code, but that's not anywhere in your example json.

Get JSON response when request post by volley

I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button nothing show up in Listview !!
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
SupportActivity.java
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aaa/getticket.php";
private RequestQueue requestQueue1;
int i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("error")) {
Toast.makeText(supportActivity.this, "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject ticket ;
JSONArray jsonArray = new JSONArray("responseticket");
ticket = jsonArray.getJSONObject(Integer.parseInt(response));
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
SupportAdapter.java
public class supportAdapter extends ArrayAdapter<supportContent> {
private Context context;
private List<supportContent> contents;
public supportAdapter(Context context, List<supportContent> con){
super(context, R.layout.supportcontent, con);
this.contents = con;
}
#Override
public int getCount(){
return contents.size();
}
public View getView(int position, View convertview, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(getContext());
View supcon = inflater.inflate(R.layout.supportcontent, null);
TextView ticketnumber = (TextView)supcon.findViewById(R.id.ticketnumber);
ticketnumber.setText(contents.get(position).getTicketnumber());
TextView supportsubject = (TextView)supcon.findViewById(R.id.supportsubject);
supportsubject.setText(contents.get(position).getSubject());
TextView response = (TextView)supcon.findViewById(R.id.response);
response.setText(contents.get(position).getResponse());
return supcon;
}
}
Parse your response as below -
JSONObject jObj = new JSONObject(response);
JSONArray jResponseTicketarray = jObj.getJSONArray("responseticket");
JSONObject jTicket = jResponseTicketarray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
response - returned Json response in onResponse() mth.
jResponseTicketarray.getJSONObject(0); - here '0' is first element in ResponseTicketArray. If der are multiple object u might wanna iterate thr loop and extract required fields.
Modify below code too -
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
to below -
supportContent support = new supportContent();
support.setTicketnumber(TicketNumber);
support.setSubject(Subject);
support.setResponse(Response);

How to display the data from mySQL in listview in android?

I can insert data into database but now face the problem that cannot retrieve data from the database and display in listview in android. Here is my coding part for retrieve data. Hope someone can help to solve this, thank you.
package com.example.iuum;
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.19.229.212/webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum1a);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
public void clickbtnWrite(View v) {
Intent i = new Intent(Forum1a.this, AddForum.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singelpost, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum1a.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Add ListView in activity_forum1a.xml
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
Take ListView reference
private ListView mList;
Initialize it in onCreate
mList = (ListView) findViewById(R.id.list_view);
Take ListAdapter class Refernce
private ListAdapter listAdapter;
Add setListAdapter method
public void setListAdapter(ListAdapter listAdapter) {
this.listAdapter = listAdapter;
mList.setAdapter(listAdapter);
}
Change updateList method to
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.test, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
}
and perform item click operation outside from the method, by implementing onItemClickListener

Where do I put the function to display the loading process?

I want to display a loading process when my application is loading data from the database.
This is my Java file.
Where do I have to put the function to display the loading process?
public class AksesServerActivity extends ListActivity {
private static String link_url = "http://plnskh.zz.mu/android/berita/cekdaftar.php";
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>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
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 = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
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();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, daftar_artikel,
R.layout.list_item,
new String[] { AR_JUDUL, AR_CONTENT, AR_ID}, new int[] {
R.id.judul, R.id.content, R.id.kode});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode = ((TextView) view.findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(AksesServerActivity.this, DetailAksesServer.class);
in.putExtra(AR_ID, kode);
startActivity(in);
}
});
}
}
public class LongOperation extends AsyncTask<String, String, String>
{
ProgressDialog pdialog;
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
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 = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdialog.dismiss();
this.adapter_listview();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(NewsActivity.this);
pdialog.setMessage("Loading");
pdialog.show();
}
}
for more clarification about asynchronous task and its methods, check here
You must use AsyncTask class, override doInBackground method to perform your databse fetch, onPreExecute method to show your loading and onPostExecute to hide it. you can refer AsynTask process and AsynTask post for more information

Categories

Resources