NullPointerException onTextChanged [duplicate] - java

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

Related

Json parsing errors at android

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.

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails 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... params) {
// 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
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} 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);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// 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
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);

Simple Android Image Parsing

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.

how to create json image and text list view? Please explain the correct format for onitemclicklistener with example?

I am tring to onitemclicklistener is working but content is not displayed.
Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG_details = "details";
ListView mListView; String tv_country_details;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://http://192.168.0.200/android/count.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** 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 while downloading url", 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>implements OnItemClickListener
{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
String visibility = jObject.getString("visibility");
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "flag","details"};
// Ids of views in listview_layout
int[] to = { R.id.iv_flag,R.id.tv_country_details};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
String tv_country_details = getIntent().getStringExtra("details");
Intent intent = new Intent(MainActivity.this, SingleMenuItemActivity.class);
intent.putExtra("TAG_details", tv_country_details);
startActivity(intent);; }
});
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
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);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
}
}
/** 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 im,gUrl;
gUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(gUrl);
// 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();
}
}
## Json Parser Code ##
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject) {
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("countries");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries) {
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String flag="";
String currencyName = "";
try {
flag = jCountry.getString("flag");
currencyName = jCountry.getJSONObject("currency").getString("currencyname");
String details = currencyName ;
country.put("flag", R.drawable.blank);
country.put("flag_path", flag);
country.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return country; }
public static Object optJSONObject(int arg2) {
// TODO Auto-generated method stub
return null;
}
public static boolean isNull(int arg2) {
// TODO Auto-generated method stub
return false;
}
}
## SingleMenuitemActivity code ##
List item
public class SingleMenuItemActivity extends Activity {
// JSON node keys
String tv_country_details;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
Intent i = getIntent();
// Get the result of rank
tv_country_details = i.getStringExtra("tv_country_details");
// Locate the TextViews in singleitemview.xml
TextView txttv_country_details = (TextView) findViewById(R.id.tv_country_details);
// Set results to the TextViews
txttv_country_details.setText(tv_country_details);
}
}

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