Pass fragment activity context to custom listview adapter - java

I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!

A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}

you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode

Related

Android JSON Parsing images into imageview with cached thumbnails

I'm trying to develop an app which works by parsing json and adding parsed json into Imageview. I set a GridView and Imageview into it as a row. When I run app, pictures get parsed as well but when I scroll down, the thumbnails get lost.
The video at this URL Json thumbs shows what I mean.
Here my MainActivity.java:
package berkantkz.wallstation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.baoyz.widget.PullRefreshLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar tool_bar = (Toolbar) findViewById(R.id.tool_bar);
tool_bar.setTitle(R.string.app_name);
tool_bar.setLogo(R.mipmap.ic_launcher);
ProgressBar spinner = (ProgressBar) findViewById(R.id.spinner);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("https://raw.githubusercontent.com/berkantkz/misc/master/sample.json");
PullRefreshLayout layout = (PullRefreshLayout) findViewById(R.id.swipeRefreshLayout);
// listen refresh event
layout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// start refresh
Intent i = new Intent(MainActivity.this, MainActivity.class); //your class
startActivity(i);
finish();
}
});
// refresh complete
layout.setRefreshing(false);
final GridView listview = (GridView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long id) {
//
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.GONE);
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearlayout.setBackgroundColor(getResources().getColor(R.color.black));
//TextView tv = (TextView) findViewById(R.id.tvName);
//tv.setVisibility(View.VISIBLE);
final ImageView iv = (ImageView) findViewById(R.id.expanded_image);
Picasso.with(MainActivity.this)
.load(actorsList.get(position).getImage())
.into(iv, new Callback() {
#Override
public void onSuccess() {
pb.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
iv.setVisibility(View.VISIBLE);
listview.setVisibility(View.GONE);
//
}
});
}
#Override
public void onBackPressed() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.VISIBLE);
ImageView iv = (ImageView) findViewById(R.id.expanded_image);
iv.setVisibility(View.GONE);
GridView listview = (GridView) findViewById(R.id.list);
listview.setVisibility(View.VISIBLE);
LinearLayout ln = (LinearLayout) findViewById(R.id.LinearLayout1);
ln.setBackgroundColor(getResources().getColor(R.color.default_bg));
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.GONE);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.refresh) {
// TODO Auto-generated method stub
}
return super.onOptionsItemSelected(item);
}
}
Actors.java
package berkantkz.wallstation;
/**
* Created by berka on 1.12.2016.
*/
public class Actors {
private String name;
private String description;
private String image;
public Actors() {
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
package berkantkz.wallstation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by berka on 25.11.2016.
*/
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
Log.d("Deneme", "birinci");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("Deneme", "iki");
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
//holder.tvName = (TextView) v.findViewById(R.id.tvName);
//holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.transparent);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
//holder.tvName.setText(actorList.get(position).getName());
//holder.tvDescription.setText(actorList.get(position).getDescription());
return v;
}
static class ViewHolder {
public ImageView imageview;
//public TextView tvName;
//public TextView tvDescription;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to display only selected data from database in Android Studio

My program is designed to search the database for the specific name entered, then the program will only display the row of the specific name. However, my code is unable to display the specific data. I have tried many kind of ways but it is unable to solve my problem. My php code is as below:
<?php
$con = mysql_connect('mysql17.000webhost.com', 'a2634311_minzhe', 'MZRules0118');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2634311_gdp", $con);
$result = mysql_query("SELECT * FROM groupdesign");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
My activity code is as below:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
public class PatientLocation extends ActionBarActivity {
private ListView PatientLocationListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.PatientLocationListView = (ListView) this.findViewById(R.id.listView4);
new Location().execute(new API_Connector());
}
public void setListAdapter(JSONArray jsonArray) {
SharedPreferences settings = getSharedPreferences("myprefrences", Context.MODE_PRIVATE);
String name = settings.getString("name", "");
this.PatientLocationListView.setAdapter(new PatientAdapter(jsonArray,name, this));
}
private class Location extends AsyncTask<API_Connector, Long, JSONArray> {
#Override
protected JSONArray doInBackground(API_Connector... params) {
//it is executed on Background thread
return params[0].GetPatientLocation();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
// check for null
if (jsonArray != null) {
// only pass the array to adapter if it is not null
setListAdapter(jsonArray);
} else {
Toast.makeText(PatientLocation.this, "Null Array returned", Toast.LENGTH_SHORT).show();
}
}
}
}
class PatientAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
String pname;
private static LayoutInflater inflater = null;
public PatientAdapter(JSONArray jsonArray, String name, Activity a) {
this.dataArray = jsonArray;
this.activity = a;
this.pname = name;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String patientname,patientlocation;
//set up convert view if it is null
ListCell cell = new ListCell();
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_position, null);
cell.patient_name = (TextView) convertView.findViewById(R.id.textView30);
cell.patient_location = (TextView) convertView.findViewById(R.id.textView31);
convertView.setTag(cell);
}
else {
cell = (ListCell) convertView.getTag();
}
//change the data of the cell
try {
for(int i=0;i<dataArray.length();i++) {
JSONObject jsonObject = this.dataArray.getJSONObject(i);
if(pname == jsonObject.getString("Name")) {
patientname = jsonObject.getString("Name");
patientlocation = jsonObject.getString("Location");
cell.patient_name.setText(patientname);
cell.patient_location.setText(patientlocation);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView patient_name;
private TextView patient_location;
}
}
Where is WHERE clause in your query in php code? You need to set some conditions to match specific name in query like if you want to search 'abcd' then your query should be SELECT * FROM groupdesign WHERE column_name = "abcd". This will return records which contanis value "abcd" from your database

Android notifyDataSetChanged()' on a null object reference CustomListAdapter

I've got a problem ! I've got this code :
HorairesActivity.java :
package activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import adapter.CustomListAdapterHoraires;
import app.AppController;
import model.Horaires;
public class HorairesActivity extends ActionBarActivity {
private Toolbar mToolbar;
private ListView listView3;
private List<Horaires> horairesList = new ArrayList<Horaires>();
private CustomListAdapterHoraires adapter;
private static final String TAG = MainActivity.class.getSimpleName();
private SwipeRefreshLayout swipeLayout3;
final Random rnd = new Random();
private String configGrade;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
View headerView = getLayoutInflater().inflate(
R.layout.view_list_item_header, listView3, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onCreate (
final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intents = getIntent();
String id = intents.getStringExtra("libelle");
setContentView(R.layout.activity_horaires);
View searchContainer = findViewById(R.id.search_container);
final EditText toolbarSearchView = (EditText) findViewById(R.id.search);
ImageView searchClearButton = (ImageView) findViewById(R.id.search_clear);
searchClearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toolbarSearchView.setText("");
}
});
searchContainer.setVisibility(View.GONE);
View headerView = getLayoutInflater().inflate(
R.layout.view_list_item_header, listView3, false);
final ImageView img = (ImageView) headerView.findViewById(R.id.imageView);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(3);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
listView3 = (ListView) findViewById(R.id.list_horaires);
listView3.addHeaderView(headerView);
TextView t = (TextView) findViewById(R.id.headertext);
t.setText(id);
listView3.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
View headerView = view.findViewById(R.id.header);
final float mTop = -headerView.getTop();
float height = headerView.getHeight();
if (mTop > height) {
// ignore
return;
}
View imgView = headerView.findViewById(R.id.header);
imgView.setTranslationY(mTop / 2f);
}
});
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
final String url = "" + "https://open.tan.fr/ewp/horairesarret.json/" + intent.getExtras().getString("id") + "/" + intent.getExtras().getString("ligne") + "/" + intent.getExtras().getString("sens") + "";
Toast.makeText(getApplicationContext(), intent.getExtras().getString("text"), Toast.LENGTH_LONG).show();
Log.d("Test", url);
listView3 = (ListView) findViewById(R.id.list_horaires);
// movieList is an empty array at this point.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
Horaires horaires = new Horaires();
ArrayList<String> listdata = new ArrayList<String>();
JSONArray configJsonArray = response.getJSONArray("horaires");
for(int configIterator = 0; configIterator < configJsonArray.length(); configIterator++){
JSONObject innerConfigObj = configJsonArray.getJSONObject(configIterator);
configGrade = innerConfigObj.getString("heure");
JSONArray courseJsonArray = innerConfigObj.getJSONArray("passages");
for(int courseIterator = 0; courseIterator < courseJsonArray.length(); courseIterator++){
listdata.add(courseJsonArray.get(courseIterator).toString());
}
}
horaires.setHeure(configGrade);
horaires.setPassages(listdata);
horairesList.add(horaires);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
swipeLayout3 = (SwipeRefreshLayout) findViewById(R.id.container3);
swipeLayout3.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeLayout3.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
horairesList.clear();
adapter.notifyDataSetChanged();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
Horaires horaires = new Horaires();
ArrayList<String> listdata = new ArrayList<String>();
JSONArray configJsonArray = response.getJSONArray("horaires");
for(int configIterator = 0; configIterator < configJsonArray.length(); configIterator++){
JSONObject innerConfigObj = configJsonArray.getJSONObject(configIterator);
configGrade = innerConfigObj.getString("heure");
JSONArray courseJsonArray = innerConfigObj.getJSONArray("passages");
for(int courseIterator = 0; courseIterator < courseJsonArray.length(); courseIterator++){
listdata.add(courseJsonArray.get(courseIterator).toString());
}
}
horaires.setHeure(configGrade);
horaires.setPassages(listdata);
horairesList.add(horaires);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
swipeLayout3.setRefreshing(false);
}
});
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
public void onActivityCreated(Bundle savedInstanceState) {
adapter = new CustomListAdapterHoraires(getParent(), horairesList);
listView3.setAdapter(adapter);
}
}
ANd i've got CustomListAdapterHoraires.java :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Horaires;
public class CustomListAdapterHoraires extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Horaires> horaireItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterHoraires(Activity activity, List<Horaires> horaireItems) {
this.activity = activity;
this.horaireItems = horaireItems;
}
#Override
public int getCount() {
return horaireItems.size();
}
#Override
public Object getItem(int location) {
return horaireItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView heure = (TextView) convertView.findViewById(R.id.heure);
TextView passage = (TextView) convertView.findViewById(R.id.passage);
// getting movie data for the row
Horaires m = horaireItems.get(position);
// title
heure.setText(m.getHeure());
String ligneStr = "";
for (String str : m.getPassages()) {
ligneStr += str + ", ";
}
ligneStr = ligneStr.length() > 0 ? ligneStr.substring(0,
ligneStr.length() - 2) : ligneStr;
passage.setText(ligneStr);
return convertView;
}
}
And when i test i've got this in log :
java.lang.NullPointerException: Attempt to invoke virtual method 'void
adapter.CustomListAdapterHoraires.notifyDataSetChanged()' on a null
object reference
I don't know where is the problem.
move this code to the onCreate, prior to doing any requests and change getParent to this
public void onActivityCreated(Bundle savedInstanceState) {
adapter = new CustomListAdapterHoraires(this, horairesList);
listView3.setAdapter(adapter);
}

read string from edit text, using parse?

Ok the app populates the list view from a Url(json). But I want to change the app so that the list view is populated by user input. How do I go about this. Here is my main activity so far:
package ionictech.com.onspot;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import ionictech.com.onspot.adapter.FeedListAdapter;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
public class OnSpotActivity extends ActionBarActivity {
private DrawerLayout drawerLayout;
private String[] Menu;
private static final String TAG = OnSpotActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_spot);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem> ();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable (Color.parseColor ("#ffba00")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getmInstance ().getmRequestQueue ().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d (TAG, "Response: " + response.toString ());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getmInstance ().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And here is my feed item list class:
package ionictech.com.onspot.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import ionictech.com.onspot.FeedImageView;
import ionictech.com.onspot.R;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
/**
* Created by MarcusLee on 9/30/14.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getmInstance ().getImageLoader();
public FeedListAdapter (Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getmInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString (
Long.parseLong (item.getTimeStamp ()),
System.currentTimeMillis (), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty (item.getStatus ())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml ("<a href=\"" + item.getUrl () + "\">"
+ item.getUrl () + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance ());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
I know that the input has to be sent to a server and then read and put into the list view, I just don't know the methods and such. Any help would be most grateful!

How to make a custom listview clickable

I'm having trouble making a listview item clickable. I've tried if statments, onclicklisteners and I'm still not having any success, does anyone know how to do this? I also have another class to get the strings, but I don't think it is needed. If you could help me out with this, I would appreciate it! Thanks!Here is my code:
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity{
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(MainActivity.this,
"Please wait...", "Retrieving data ...", true);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
m_orders = new ArrayList<Order>();
Order o1 = new Order();
o1.setOrderName("Item 1");
o1.setOrderStatus("2012");
o1.setorderpic(R.drawable.bulb);
Order o2 = new Order();
o2.setOrderName("Item 2");
o2.setOrderStatus("Completed");
o2.setorderpic(R.drawable.bulb);
m_orders.add(o1);
m_orders.add(o2);
Thread.sleep(5000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Order o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
ImageView ct = (ImageView) v.findViewById(R.id.icon);
if (tt != null) {
tt.setText("Name: "+o.getOrderName()); }
if(bt != null){
bt.setText("Status: "+ o.getOrderStatus());
}
if(ct !=null){
ct.setImageResource(o.getorderpic());
}
}
return v;
}
}
You can use view's OnClickListener in getView() of your custom adapter
v.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// do something on click
}
});
http://developer.android.com/reference/android/view/View.OnClickListener.html
You should override ListActivity's onListItemClick method. This is what ListActivity is made for.
onListItemClick()

Categories

Resources