I am a beginner in Android programming. I'm trying to put an ID identifier coming from MySQL database using JSON to my listview items but I can't make it work. When i click on an item it should probably give the id of the item I clicked but it is not working and all I can get is a false.
public class MessagingListFragment extends Fragment {
private String jsonResult;
private String url = "http://10.0.2.2/mobile/get_my_ins.php";
private ListView listView;
List<NameValuePair> nameValuePairs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.messaging_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
accessWebService();
return rootView;
}
// Async Task to access the web
#SuppressLint("NewApi")
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("stud_id",MainActivity.user_id));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
}
}// end async task
public void accessWebService() {
try{
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 3", Toast.LENGTH_LONG).show();
}
}
// build hash set for list view
public void ListDrawer() {
List<Map<String, String>> classList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("recipient");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String friend = jsonChildNode.optString("last_name") + ", " + jsonChildNode.optString("first_name");
String outPut = friend;
classList.add(createMsgList("recipient", outPut));
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.getMessage().toString() + " 1", Toast.LENGTH_LONG).show();
}
try{
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity() , classList,
android.R.layout.simple_list_item_1, new String[] { "recipient" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int i,
long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
Toast.makeText(getActivity(), e.getMessage().toString() + " 2", Toast.LENGTH_LONG).show();
}
}
private HashMap<String, String> createMsgList(String name, String subject) {
HashMap<String, String> friendList = new HashMap<String, String>();
friendList.put(name, subject);
return friendList;
}
}
You are popping up a Toast with listView.getId() as the textual content. This will always give you the ID of the listview that is containing your list items.
If you want to grab the data for the view, you will either need to use the position parameter (int i in the onItemClick method), or you can try to grab the data from the View v if it is a custom view.
For example, instead of passing in a String array into your adapter, you can keep a reference to the array and find the data you are looking for with myArray[i].
by calling listView.getId() you requested the listview id not the item inside listview
change
Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();
to
Toast.makeText(getActivity(), "my id and position = "+i, Toast.LENGTH_LONG).show();
i is the item position inside listview and JSONArray
hope this information helpful to you
Related
I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.
I'm creating a simple search activity using EditText, ListView, JSON and Database, Every time i enter text in EditText, the listview must update(I'm using mysql, Select query LIKE), where the ListView that contains Items from Database using JSON, the items must be updated from the given condition using LIKE method, but it keeps in duplicating item in ListView every time i enter text.
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
name = inputSearch.getText().toString();
searcher(name);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
String result;
private void searcher(String searched){
class searching extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramSearched = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://....p.com/searchD.php?name=" + paramSearched);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream is = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
result = stringBuilder.toString();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject obj = new JSONObject(result);
nameslist = obj.getJSONArray("list");
for(int i = 0; i < nameslist.length(); i++){
JSONObject c = nameslist.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("Name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", id);
map.put("Name", name);
listofnames.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Searching Name. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Search.this, listofnames,
R.layout.list_item1, new String[]{"ID",
"Name"},
new int[]{R.id.pid, R.id.name});
lv.setAdapter(adapter);
}
});
adapter.notifyDataSetChanged();
}
}
searching sh = new searching();
sh.execute(searched);
}
I think you should clear the "listofnames" list before you add new data into it to keep the list data newest and not duplicated.
I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
Right now, I have an Activity that displays 10 listings from a JSON array. Next, on the swipe of an ImageView, I want to clear the ListView and display the next 10 (as a "next page" type thing). So, right now I do this
view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) {
#Override
public void onSwipeLeft() {
//clear adapter
adapter.clear();
//get listings 10-20
startLoop = 10;
endLoop = 20;
//call asynctask to display locations
FillLocations myFill = new FillLocations();
myFill.execute();
Toast.makeText(getApplicationContext(), "Left",
Toast.LENGTH_LONG).show();
}
and when I swipe it diisplays ONE item and I get this error
Error Parsing Data android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
What am I doing wrong? Thanks!
Full code:
public class MainActivity extends ActionBarActivity {
ListView listView;
int startLoop, endLoop;
TextView test;
ArrayList<Location> arrayOfLocations;
LocationAdapter adapter;
ImageView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLoop = 0;
endLoop = 10;
listView = (ListView) findViewById(R.id.listView1);
// Construct the data source
arrayOfLocations = new ArrayList<Location>();
// Create the adapter to convert the array to views
adapter = new LocationAdapter(this, arrayOfLocations);
FillLocations myFill = new FillLocations();
myFill.execute();
view = (ImageView) findViewById(R.id.imageView1);
view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) {
#Override
public void onSwipeLeft() {
adapter.clear();
startLoop = 10;
endLoop = 20;
FillLocations myFill = new FillLocations();
myFill.execute();
Toast.makeText(getApplicationContext(), "Left",
Toast.LENGTH_LONG).show();
}
});
}
private class FillLocations extends AsyncTask<Integer, Void, String> {
String msg = "Done";
protected void onPreExecute() {
progress.show();
}
// Decode image in background.
#Override
protected String doInBackground(Integer... params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://americanfarmstands.com/places/");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
// resultView.setText("connected");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = startLoop; i < endLoop; i++) {
//Toast.makeText(getApplicationContext(), i,
// Toast.LENGTH_LONG).show();
final JSONObject json = jArray.getJSONObject(i);
// counter++;
String initialURL = "http://afs.spotcontent.com/img/Places/Icons/";
final String updatedURL = initialURL + json.getInt("ID")
+ ".jpg";
Bitmap bitmap2 = null;
try {
bitmap2 = BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
return msg;
}
protected void onPostExecute(String msg) {
// Attach the adapter to a ListView
//ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
progress.dismiss();
}
}
Location Adapter:
public class LocationAdapter extends ArrayAdapter<Location> {
public LocationAdapter(Context context, ArrayList<Location> locations) {
super(context, R.layout.item_location, locations);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Location location = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails);
TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance);
TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours);
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
// Populate the data into the template view using the data object
tvName.setText(location.name);
tvDetails.setText(location.details);
tvDistance.setText(location.distance);
tvHours.setText(location.hours);
ivIcon.setImageBitmap(location.icon);
// Return the completed view to render on screen
return convertView;
}
}
EDIT: Updated Code:
for (int i = startLoop; i < endLoop; i++) {
// Toast.makeText(getApplicationContext(), i,
// Toast.LENGTH_LONG).show();
final JSONObject json = jArray.getJSONObject(i);
// counter++;
String initialURL = "http://afs.spotcontent.com/img/Places/Icons/";
final String updatedURL = initialURL + json.getInt("ID")
+ ".jpg";
final Bitmap bitmap2 =BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
//try {
// bitmap2 = BitmapFactory
// .decodeStream((InputStream) new URL(updatedURL)
// .getContent());
//} catch (MalformedURLException e) {
// e.printStackTrace();
//} catch (IOException e) {
// e.printStackTrace();
//}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The adapter must be updated from the UI thread.
You should change your AsyncTask into AsyncTask<Integer, Void, List<Location>>, and have the loop in on doInBackground() create a collection of Location and return it (instead of directly changing the adapter).
Finally, in onPostExecute(List<Location> result), do:
adapter.clear();
for (Location location : result)
adapter.add(location);
The error is clearly saying that you are trying to update View from a different thread(doInBackground) that catch an exception CalledFromWrongThreadException.
This line is the cause of the problem
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
that it should be called in the Main thread.
solution:
Call the main thread and update the adapter from there
example:
try {
final Bitmap bitmap2 = BitmapFactory
.decodeStream((InputStream) new URL(updatedURL)
.getContent());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Move this bunch of code to onPostExecute
protected void onPostExecute(String msg) {
try {
adapter.add(new Location(bitmap2, json
.getString("PlaceTitle"), json
.getString("PlaceDetails"), json
.getString("PlaceDistance"), json
.getString("PlaceUpdatedTime")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Attach the adapter to a ListView
//ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
progress.dismiss();
}
Make Bitmap a class variable.
I am having a problem with my setOnClickListener. I can not figure out what the code is i need for it. What i am trying to do is once the item is clicked on in the list view it opens up a new activity. in my code the list view is in the MainActivity. and i want it to open up the Homework activity. So my question is, can anybody help me figure out what i need to put in for it to work correctly and open up Homework.java? when it opens up Homework.java it would show the item clicked in the list view as the header. then nothing in the body.
MainActivity.class:
public class VideoListTask extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute (Void result) {
dialog.getProgress();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params)
{
HttpClient client = new DefaultHttpClient();
//HttpGet getRequest = new HttpGet(feedUrl);
Date now = new Date();
HttpGet getRequest = new HttpGet(canvasUrl + "courses? include[]=term&state=available");
getRequest.setHeader("Authorization","Bearer " + canvasApiKey); //uses your key to access your data
try
{
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode != 200)
{
return null;
}
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine())!=null)
{
builder.append(line);
}
String jsonData = builder.toString();
//JSONObject json = new JSONObject(jsonData);
//JSONObject data = json.getJSONObject("data");
//JSONArray items = data.getJSONArray("items");
JSONArray courses = new JSONArray(jsonData);
//for(int i =0; i<items.length(); i++)
//{
// JSONObject video = items.getJSONObject(i);
// videoArrayList.add(video.getString("title"));
//}
for(int i = 0; i<courses.length(); i++)
{
JSONObject course = courses.getJSONObject(i);
JSONObject term = course.getJSONObject("term");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date enddate = format.parse(term.getString("end_at"));
Date startdate = format.parse(term.getString("start_at"));
if (now.after(startdate) && now.before(enddate))
{
videoArrayList.add(course.getString("name"));
}
} catch (Exception e) {
//videoArrayList.add(course.getString("name"));//include if you want undated courses
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
THIS IS WHERE I NEED TO PUT THE ONCLICK LISTENER IN.
}
If Homework.java is your second activity you can set a click listener in this way
Main Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
startActivity(new Intent(MainActivity.this, Homework.class));
}
});
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Class<?> ourClass=Class.forName("com.example.projname.Homework");
Intent ourIntent= new Intent(MainActivity.this,ourClass);
ourIntent.putExtra("matrix", m);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
});
The data you pass using putExtra will be available to you in the Homeactivity.java