I'm attempting to parse image URLs and show the images in a ListView, but I continue to receive the ProtocalNotFound Exception/JSON Exception No value for null. I am pretty sure I'm close to translating the image URLs into bitmaps, but I'm off by something small. Any ideas for the right approach would be helpful. My class is below including the URL for the feed. Right now, I'm trying to convert the image URL in the loadImageFromWebOperations method. Please let me know if you need more information.
Android Class:
public class mainViewController extends ListFragment
{
mainViewController context = this;
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
//private static final String READ_COMMENTS_URL = "https://shipstudent.com/androidapp/comments.php";
private static final String READ_COMMENTS_URL = "https://shipstudent.com/complaint_desk/androidcentralwall.php";
// JSON IDS:
#SuppressWarnings("unused")
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
#SuppressWarnings("unused")
private static final String TAG_POST_ID = "IDPosts";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "body";
private static final String TAG_PROFILE_PICTURE = "profile_picture";
//private static final String TAG_POSTED = "posted";
// it's important to note that the message is both in the parent branch of
// our JSON tree that displays a "Post Available" or a "No Post Available"
// message,
// and there is also a message for each individual post, listed under the
// "posts"
// category, that displays what the user typed as their message.
// An array of all of our comments
private JSONArray allPosts = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
public mainViewController()
{
}
String[] mainFeed = {};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// // TODO Auto-generated method stub
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(
// inflater.getContext(), android.R.layout.simple_list_item_1,
// mainFeed);
//
// setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
// Intent i = new Intent(ReadComments.this, writePostViewController.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 {
allPosts = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < allPosts.length(); i++) {
JSONObject c = allPosts.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);
File sdCard = Environment.getExternalStorageDirectory();
String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(" ", "%20"),sdCard.getAbsolutePath() + "/dir1/dir2"));
// String profile_picture = c.getString(TAG_PROFILE_PICTURE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_PROFILE_PICTURE, profile_picture);
// adding HashList to ArrayList
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#SuppressWarnings("resource")
public static String loadImageFromWebOperations(String url, String path) {
try {
InputStream is = (InputStream) new URL(url).getContent();
System.out.println(path);
File f = new File(path);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
try {
byte[] b = new byte[100];
int l = 0;
while ((l = is.read(b)) != -1)
fos.write(b, 0, l);
} catch (Exception e) {
}
return f.getAbsolutePath();
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this.getActivity(), mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME, TAG_PROFILE_PICTURE }, new int[] { R.id.title, R.id.message,
R.id.username ,R.id.imageView1});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(mainViewController.this);
// pDialog.setMessage("Loading Posts...");
// 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();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
}
Logcat:
09-08 21:29:01.281: I/System.out(17363): Exc=java.net.MalformedURLException: Protocol not found: profile_picture
09-08 21:29:01.281: W/System.err(17363): org.json.JSONException: No value for null
09-08 21:29:01.321: W/System.err(17363): at org.json.JSONObject.get(JSONObject.java:355)
09-08 21:29:01.321: W/System.err(17363): at org.json.JSONObject.getString(JSONObject.java:515)
09-08 21:29:01.321: W/System.err(17363): at com.rynovation.kline.mainViewController.updateJSONdata(mainViewController.java:128)
09-08 21:29:01.321: W/System.err(17363): at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:230)
09-08 21:29:01.371: W/System.err(17363): at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:1)
09-08 21:29:01.371: W/System.err(17363): at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-08 21:29:01.371: W/System.err(17363): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-08 21:29:01.371: W/System.err(17363): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-08 21:29:01.371: W/System.err(17363): at java.lang.Thread.run(Thread.java:841)
The problem is here
String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(" ", "%20"),sdCard.getAbsolutePath() + "/dir1/dir2"));
First get they value for key and then load the url.
Related
I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
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();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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 from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am using a http request to get the data in JSON format which loads the image as well. I am trying to implement onTextChanged function but it always crashes whenever I enter any alphabet into the EditText box.
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
StoreJSONParser countryJsonParser = new StoreJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
//StoreJSONParser countryJsonParser = new StoreJSONParser();
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
//adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
return adapter;
}
onPostExecute
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
Log.d("What is country", String.valueOf(countries));
mListView.setAdapter(adapter);
searchBox = (EditText)findViewById(R.id.searchBox);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ChooseCategory.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ChooseCategory.this.adapter.getFilter().filter(arg0);
}
});
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
The error from logcat:
java.lang.NullPointerException
at ChooseCategory$ListViewLoaderTask$1.onTextChanged(ChooseCategory.java:196)
at android.widget.TextView.sendOnTextChanged(TextView.java:7408)
at android.widget.TextView.handleTextChanged(TextView.java:7467)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9183)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:223)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:136)
at android.widget.TextView.doKeyDown(TextView.java:5532)
at android.widget.TextView.onKeyDown(TextView.java:5343)
at android.view.KeyEvent.dispatch(KeyEvent.java:2640)
at android.view.View.dispatchKeyEvent(View.java:7665)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1408)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1408)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1408)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1408)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:2035)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1505)
at android.app.Activity.dispatchKeyEvent(Activity.java:2418)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1962)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3852)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3826)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3525)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3582)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3558)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3718)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2010)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1704)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1695)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1987)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
java.lang.NullPointerException
at ChooseCategory$ListViewLoaderTask$1.onTextChanged
Please dont make this as a duplicate. I have seen that post and I still can't fix it. That is why I'm posting here.
This is the full code for ChooseCategory.java
public class ChooseCategory extends Activity {
ListView mListView;
EditText searchBox;
SimpleAdapter adapter;
JSONObject jObject;
StoreJSONParser countryJsonParser = new StoreJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
// Keys used in Hashmap
String[] from = { "country","flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.storename,R.id.icon,R.id.details};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.list);
// URL to the JSON data
String strUrl = "http://10.0.2.2/get_stores.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception:", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
StoreJSONParser countryJsonParser = new StoreJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
//StoreJSONParser countryJsonParser = new StoreJSONParser();
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
//adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
Log.d("What is country", String.valueOf(countries));
mListView.setAdapter(adapter);
searchBox = (EditText)findViewById(R.id.searchBox);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ChooseCategory.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ChooseCategory.this.adapter.getFilter().filter(arg0);
}
});
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Do you have a class variable named adapter ?
It seems ChooseCategory.this.adapter is not the local variables
adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
you should name the class variable mAdapter.
Change in your Asyn class as follows:
private class ListViewLoaderTask extends AsyncTask<String, Void, String>{ **//Change SimpleAdapter to String**
// Doing the parsing of xml data in a non-ui thread
#Override **//Change SimpleAdapter to String**
protected String doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
StoreJSONParser countryJsonParser = new StoreJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
//StoreJSONParser countryJsonParser = new StoreJSONParser();
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
//adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.restaurant_list, from, to);
return null;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override **//Change SimpleAdapter to String**
protected void onPostExecute(String result) {
// Setting adapter for the listview
adapter = new SimpleAdapter(ChooseCategory.this, countries, R.layout.restaurant_list, from, to);
Log.d("What is country", String.valueOf(countries));
mListView.setAdapter(adapter);
searchBox = (EditText)findViewById(R.id.searchBox);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ChooseCategory.this.adapter.getFilter().filter(arg0);
}
});
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
I think there is problem with your edittext initialization.
searchBox = (EditText)findViewById(R.id.searchBox);
move this line from onPostexcute() to OnCreate()
I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// 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.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
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
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} 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
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}
i have problem when im trying to show data in list view from my database
the error is "FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4"
. i dont understand what is it.
i hope somebody can help me
thanks
this is my code
public class FragmentMaintain extends Fragment {
ListView list;
TextView mid;
TextView pid;
TextView status;
TextView description;
TextView note;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://10.0.2.2/skripsi/json/testing.php";
//JSON Node Names
private static final String TAG_OS = "maintenance";
private static final String TAG_MID = "mid";
private static final String TAG_PID = "pid";
private static final String TAG_STATUS = "status";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_NOTE = "note";
JSONArray maintenance = null;
Button Addnotedata;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ZZZ", "ada di oncreateView maintain");
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_maintain, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mid = (TextView) getActivity().findViewById(R.id.mid);
pid = (TextView) getActivity().findViewById(R.id.pid);
status = (TextView) getActivity().findViewById(R.id.status);
description = (TextView) getActivity().findViewById(R.id.description);
note = (TextView) getActivity().findViewById(R.id.note);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
//String pid = getArguments().getString("pid");
//List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("pid", pid));
JSONParser jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequestWithoutParams(url);
//Log.d("TES", pid+", "+ json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
maintenance = json.getJSONArray(TAG_OS);
for(int i = 0; i < maintenance.length(); i++){
JSONObject c = maintenance.getJSONObject(i);
// Storing JSON item in a Variable
String mid = c.getString(TAG_MID);
String pid = c.getString(TAG_PID);
String status = c.getString(TAG_STATUS);
String description = c.getString(TAG_DESCRIPTION);
String note = c.getString(TAG_NOTE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_MID, mid);
map.put(TAG_PID, pid);
map.put(TAG_STATUS, status);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_NOTE, note);
oslist.add(map);
list=(ListView) getActivity().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_maintain,
new String[] { TAG_MID,TAG_PID, TAG_STATUS, TAG_NOTE}, new int[] {
R.id.mid,R.id.pid, R.id.status, R.id.description, R.id.note});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " + oslist.get(+position).get("pid"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and this my logcat
10-10 00:10:50.575 2004-2004/com.example.blackcustomzier.skripsi
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:160)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:2177)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillFromTop(ListView.java:736)
at android.widget.ListView.layoutChildren(ListView.java:1655)
at android.widget.AbsListView.onLayout(AbsListView.java:2012)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
If the length is 4, max index should be 3 as the index starts from 0.
Try this way,hope this will help you to solve your problem.
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,R.layout.list_maintain,new String[] {TAG_MID,TAG_PID,TAG_STATUS,TAG_DESCRIPTION,TAG_NOTE}, new int[] { R.id.mid,R.id.pid, R.id.status, R.id.description, R.id.note});
You are missing to pass TAG_DESCRIPTION in String Array at adapter initialization.
When you create SimpleAdapter the 4th and 5th arguments need to be same size.
So strings of 4th argument will be used as keys to fill view with value of the map which is 3rd argument of constructor.
And the way matching a view with a key is specifying them in 4th and 5th arguments which are containing keys and containing ids of views respectively, to have same index in each array.
See this
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