FATAL EXCEPTION: main java.lang.ArrayIndexOutOfBoundsException: - java

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

Related

search filter for Listview [duplicate]

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

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

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

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

How to pass ID of one JSON to next Activity?

hello I am new to android in my app i have one ListFragment activity in which i am getting data perfectly where i have list of users now i want that after click on any user i need to show their profile
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_MATCH_ID="match_detail_id";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
String user_match_id;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://abcd.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String,String>> listData = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MATCH_ID, c.getString(TAG_MATCH_ID));
map.put(TAG_NAME,c.getString(TAG_NAME));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_IMAGE, c.getString(TAG_IMAGE));
map.put(TAG_CAST, c.getString(TAG_CAST));
map.put(TAG_AGE, c.getString(TAG_AGE)+" years");
map.put(TAG_LOCATION, c.getString(TAG_LOCATION));
// adding HashList to ArrayList
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return listData;
}
protected void onPostExecute( ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
if(aList==null){
aList = new ArrayList<HashMap<String, String>>();
}
aList.addAll(result);
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
public class ProfilePage extends Activity{
private ProgressDialog pDialog;
AQuery androidAQuery=new AQuery(this);
//private static final String TAG_MATCH_ID="match_detail_id";
private static final String USER_NAME="name";
private static final String USER_AGE="age";
private static final String USER_LOCATION="location";
private static final String USER_MOTHER_TONGE="mother_tounge";
private static final String USER_OCCU="occupation";
private static final String USER_INCOM="income";
private static final String USER_HEIGHT="height";
private static final String USER_MARRAGE="marital_status";
private static final String USER_RELIGION="religion";
private static final String USER_GOTRA="gotra";
private static final String USER_MANGLIK="manglik";
private static final String USER_RASHI="rashi";
private static final String USER_EDUCATION="education";
private static final String USER_EAT="eating";
private static final String USER_DRINK="drink";
private static final String USER_SMOKE="smoke";
private static final String USER_ABOUT="about_me";
private static final String USER_PIC="profile_pic";
private static String USER_URL="";
String user_match_id;
private ImageView cover;
private ImageView yes;
private ImageView no;
private ImageView sendmsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
String matchId=this.getIntent().getStringExtra("match_detail_id");
if(matchId.trim().length()>0){
USER_URL="http://abcds.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfilePage.this,"match id blank",Toast.LENGTH_LONG).show();
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
String user_location = jsonObj.getString(USER_LOCATION);
String user_mothertong = jsonObj.getString(USER_MOTHER_TONGE);
String user_occupation = jsonObj.getString(USER_OCCU);
String user_income = jsonObj.getString(USER_INCOM);
String user_height = jsonObj.getString(USER_HEIGHT);
String user_marg = jsonObj.getString(USER_MARRAGE);
String user_religion = jsonObj.getString(USER_RELIGION);
String user_gotra = jsonObj.getString(USER_GOTRA);
String user_manglik = jsonObj.getString(USER_MANGLIK);
String user_rashi = jsonObj.getString(USER_RASHI);
String user_education = jsonObj.getString(USER_EDUCATION);
String user_eat = jsonObj.getString(USER_EAT);
String user_drink = jsonObj.getString(USER_DRINK);
String user_smoke = jsonObj.getString(USER_SMOKE);
String user_about = jsonObj.getString(USER_ABOUT);
String user_pro = jsonObj.getString(USER_PIC);
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
final TextView sdetail = (TextView)findViewById(R.id.seconddetail);
final TextView tdetail = (TextView)findViewById(R.id.thirddetail);
final TextView ocdetail=(TextView)findViewById(R.id.txtoccupationdetail);
final TextView incomedetail = (TextView)findViewById(R.id.incomedetaile);
final TextView uheight = (TextView)findViewById(R.id.txtheightprofile);
final TextView umrg = (TextView)findViewById(R.id.txtmrgprofile);
final TextView ureligion = (TextView)findViewById(R.id.prohindu);
final TextView ugotra = (TextView)findViewById(R.id.gothraa);
final TextView umanglik = (TextView)findViewById(R.id.usermanglik);
final TextView urashi = (TextView)findViewById(R.id.rashi);
final TextView udegree = (TextView)findViewById(R.id.userdegree);
final TextView ueat = (TextView)findViewById(R.id.txteatprofile);
final TextView udrink = (TextView)findViewById(R.id.txtdrinkprofile);
final TextView usmoke = (TextView)findViewById(R.id.txtsmokeprofile);
final TextView uabout = (TextView)findViewById(R.id.txtabouther);
final ImageView ucover = (ImageView)findViewById(R.id.coverimage);
uname.setText(user_name);
fdetail.setText(user_age+" years");
sdetail.setText(user_location);
tdetail.setText(user_mothertong);
ocdetail.setText(user_occupation);
incomedetail.setText(user_income);
uheight.setText(user_height);
umrg.setText(user_marg);
ureligion.setText(user_religion);
ugotra.setText(user_gotra);
umanglik.setText(user_manglik);
urashi.setText(user_rashi);
udegree.setText(user_education);
ueat.setText(user_eat);
udrink.setText(user_drink);
usmoke.setText(user_smoke);
uabout.setText(user_about);
androidAQuery.id(ucover).image(user_pro, true, true);
} catch (JSONException e) {
e.printStackTrace();
}
Try to override onListItemClick in fragment :
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity(), ProfilePage.class);
intent.putExtra("match_detail_id", aList.get(position).get(TAG_MATCH_ID));
startActivity(intent);
}
Instead of manual setOnItemClickListener to listview so no required this code :
listview=(ListView)rootView.findViewById(android.R.id.list);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Intent intent=new Intent(getActivity().getApplicationContext(),ProfileEdit.class);
intent.putExtra("position", arg2);
startActivity(intent);
}
});
Note : when you use ListFragment no need to find Listview and set item click as well as setAdapter manually,directly get all method ready like setAdapter() and onListItemClick.
Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("KEY", Value);
startActivity(intent)
Try with below code:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
//get this data as below in ProfileEdit class
String matchId=this.getIntent().getStringExtra(""match_detail_id"");
if(matchId.trim().length()>0){
USER_URL="http://gujjumatch.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfileEdit.this,"match id blank",Toast.LENGTH_LONG).show();
}

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.

Categories

Resources