How can i get a single column using using android. instead of getting everything from the database. i want to get only the column where full_name="john".
DataParser.jave
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
persons.clear();
Person s=null;
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, ListView lv) {
this.c = c;
this.urlAddress = urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching....Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s==null)
{
Toast.makeText(c,"Unsuccessfull,Null
returned",Toast.LENGTH_SHORT).show();
}else
{
//CALL DATA PARSER TO PARSE
DataParser parser=new DataParser(c,lv,s);
parser.execute();
}
}
private String downloadData()
{
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
InputStream is=null;
try {
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response=new StringBuffer();
if(br != null)
{
while ((line=br.readLine()) != null)
{
response.append(line+"\n");
}
br.close();
}else
{
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Connector.java
public class Connector {
public static HttpURLConnection connect(String urlAddress)
{
try {
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPS
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Person.java
public class Person {
int id;
String full_name, sex, location;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Person> persons;
LayoutInflater inflater;
public CustomAdapter(Context c, ArrayList<Person> persons) {
this.c = c;
this.persons = persons;
//INITIALIE
inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return persons.size();
}
#Override
public Object getItem(int position) {
return persons.get(position);
}
#Override
public long getItemId(int position) {
return persons.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView=inflater.inflate(R.layout.model,parent,false);
}
TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
TextView sexTxt= (TextView) convertView.findViewById(R.id.propellantTxt);
TextView locationTxt= (TextView) convertView.findViewById(R.id.descTxt);
nameTxt.setText(persons.get(position).getFull_name());
sexTxt.setText(persons.get(position).getSex());
locationTxt.setText(persons.get(position).getLocation());
//ITEM CLICKS
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,persons.get(position).getFull_name(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
server side php file
<?php
$host = 'localhost';
$username='root';
$pwd ='';
$db ='user';
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$query=mysqli_query($con,"SELECT * FROM person");
if($query)
{
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>
mainactivity.java
public class MainActivity extends AppCompatActivity {
String urlAddress="http://localhost/Android/includes/retrive.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ListView lv= (ListView) findViewById(R.id.lv);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Downloader d=new Downloader(MainActivity.this,urlAddress,lv);
d.execute();
}
});
}
}
Got the code online and cant find a way to get a single column
It looks like the json you are using is from an API response. In that case, if you want to do it in SQL you would need to create a new api and SQL query on the server. If you want to just limit what is displaying in the loop, only parse the parts you want.
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
s = new Person();
s.setFull_name(name);
persons.add(s);
}
You would then need to also change the logic in your activity that displays the data, and only display person.name, as the rest of the properties will be null.
I recommend doing more research on consuming APIs and parsing JSON, as it appears that the code you are using does not have a database or SQL.
Related
I'm Having difficulty populating TextViews from my SQL Database. I have one column populating a spinner and then I want the Two Textviews to be populated by MySQL Columns from the same row of the spinner selection.
I cannot find the correct code to add to the OnSelectedItem portion.
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
Context c;
TextView colorDensity;
Spinner colorSpinner= findViewById(R.id.colorSpinner);
ArrayList<String> colors=new ArrayList<>();
final static String urlAddress = "http://www.burtkuntzhandjobs.org/dbcolors.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Downloader(MainActivity.this,urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this,"Select Color", Toast.LENGTH_SHORT).show();
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setIu(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner colorSpinner;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner colorSpinner) {
this.c = c;
this.urlAddress = urlAddress;
this.colorSpinner = colorSpinner;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching");
pd.show();
}
#Override
protected String doInBackground(Void...params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s == null) {
Toast.makeText(c,"Unable to Retrieve",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Success",Toast.LENGTH_SHORT).show();
DataParser parser=new DataParser(c,colorSpinner,s);
parser.execute();
}
}
private String downloadData() {
HttpURLConnection con= (HttpURLConnection) Connector.connect(urlAddress);
if(con == null) {
return null;
}
InputStream is = null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer response=new StringBuffer();
if(br != null){
while ((line=br.readLine()) !=null) {
response.append(line+"\n");
}
br.close();
} else {
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try{
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Make following changes & add required code,
1. Remove Spinner colorSpinner= findViewById(R.id.colorSpinner); from class variable.
2. Add Spinner colorSpinner= findViewById(R.id.colorSpinner); in onCreate` method.
Look this spinet,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
Spinner colorSpinner= findViewById(R.id.colorSpinner);
new Downloader(this, urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
3. Access colors list from DataParser class,
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
private static ArrayList<Colors> colorsList=new ArrayList<>(); // add this line
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setUi(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
colorsList.add(s); // add this line
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public static List<Colors> getColorsList() { // add this method
return colorsList;
}
}
4. Set density accordingly in onItemSelected() method of activity class.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<Colors> colorsList = DataParser.getColorsList();
colorDensity.setText(colorsList.get(position).getDensity());
}
I'm new coder of android and trying to get list of images in my server and database(mysql) but I got error and I don't know what is causing it...
the error is 'E/RecyclerView: No adapter attached; skipping layout' and it happen when I'm running, anyone can help me??
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private RecyclerView recyclerView;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(RecyclerView recyclerView, Context context, boolean pattern) {
this.recyclerView = recyclerView;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
imageGalleryItems = prepareData(response);
MyAdapter adapter = new MyAdapter(context, imageGalleryItems);
recyclerView.setAdapter(adapter);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
I wrote my adapter as MyAdapter.java:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context, ArrayList<ImageGalleryItem> galleryList) {
this.galleryList = galleryList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
You can setup your recyclerView and set items when data received.
activity code for setup recycler view:
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupRecyclerView();
}
private void setupRecyclerView(){
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(context);
recyclerView.setAdapter(mAdapter);
}
}
Pass adapter to async task:
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private MyAdapter mAdapter;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(MyAdapter adapter, Context context, boolean pattern) {
this.mAdapter = adapter;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
imageGalleryItems = prepareData(response);
mAdapter.setItems(imageGalleryItems);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
Adapter with setItems method:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context) {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
public void setItems(ArrayList<ImageGalleryItem> galleryList){
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
I am new in android i have applied all solutions. but
problem is not solved.
I have made separate classes for asyncTask ,adapter,Model
activity oncreate call the asyncTask class . in asyncTask adapter is called
and listview is called.
kindly help. Thanks in advance
my activity is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
CourseOutlinesTask task = new CourseOutlinesTask(CourseOutlinesActivity.this); task.execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
asyncTASK CLASS is
public class CourseOutlinesTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
Activity context;
private ArrayList<CourseModel> postList = new ArrayList<CourseModel>();
private ListView listView;
TrainerCourseAdapter adapter;
public CourseOutlinesTask(Activity context) {
context = this.context;
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//close process dialog
if (this.dialog != null) {
this.dialog.dismiss();
}
//parse json
try {
JSONObject jsonParse = new JSONObject(result);
JSONArray query = jsonParse.getJSONArray("courses");
for (int i = 0; i < query.length(); i++) {
try {
JSONObject jsonParser = query.getJSONObject(i);
CourseModel post = new CourseModel();
post.setId(jsonParser.getInt("id"));
post.setTitle(jsonParser.getString("title"));
post.setStatus(jsonParser.getString("status"));
post.setDescription(jsonParser.getString("description"));
System.out.println(post.getStatus()+"asdadasdad");
System.out.println(post);
postList.add(post);
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
System.out.println("ttttttttttttttttttttt");
listView = (ListView) context.findViewById(R.id.course_listView);
listView.setAdapter(new TrainerCourseAdapter(context,postList));
}catch (Exception e) {
System.out.println(e);
}
// Parsing json
post.setDescription(obj.getString("description"));
}
} else {
MyAppUtil.getToast(getApplicationContext(), message);
}*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
my adapter class is
public class TrainerCourseAdapter extends BaseAdapter {
private List list;
private Context context;
private static LayoutInflater inflater = null;
String [] cName;
String [] cDetail;
String [] created;
String [] cStatus;
ArrayList<CourseModel> itemList;
Context mcontext;
public TrainerCourseAdapter(Context context,List list) {
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
mcontext = context;
itemList = (ArrayList<CourseModel>) this.list;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
public void setItemList(ArrayList<CourseModel> itemList) {
this.itemList = itemList;
}
public class Holder
{
TextView c_name;
TextView c_detail;
TextView c_date ;
Button c_status;
}
#Override
public View getView(final int i, View rowView, ViewGroup viewGroup) {
Holder holder = new Holder();
rowView = inflater.inflate(R.layout.row_courses_list, null);
holder.c_name = (TextView) rowView.findViewById(R.id.txt_courseName);
holder.c_detail = (TextView) rowView.findViewById(R.id.txt_courseDetail);
holder.c_date = (TextView) rowView.findViewById(R.id.txt_courseDate);
holder.c_status = (Button) rowView.findViewById(R.id.btn_courseStatus);
final CourseModel data = itemList.get(i);
holder.c_name.setText(data.getTitle());
holder.c_detail.setText(data.getDescription());
holder.c_status.setText(data.getStatus());
holder.c_date.setText(data.getId());
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "You Clicked "+ cName[i], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
model is
public class CourseModel {
private int id;
private String title;
private String description;
private String status;
// private int totalCount;
// private int limit;
// private String offset;
public CourseModel(){
}
/*Getter for Course Model*/
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getStatus() {
return status;
}
/*Endo of Model Getter*/
/*Setter for Model*/
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setStatus(String status) {
this.status = status;
}
/*End for Model Setters*/
}
when i run app list is empty and error is
10-05 19:22:04.352 10503-10537/vu.bc110201891.btg I/OpenGLRenderer: Initialized EGL, version 1.4
10-05 19:22:04.478 10503-10537/vu.bc110201891.btg D/OpenGLRenderer: Enabling debug mode 0
10-05 19:22:04.541 10503-10537/vu.bc110201891.btg W/EGL_emulation: eglSurfaceAttrib not implemented
10-05 19:22:04.541 10503-10537/vu.bc110201891.btg W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeb9943c0, error=EGL_SUCCESS
10-05 19:22:04.718 10503-10503/vu.bc110201891.btg I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread.
10-05 19:22:05.564 10503-10503/vu.bc110201891.btg I/System.out: Rejectasdadasdad
10-05 19:22:05.564 10503-10503/vu.bc110201891.btg I/System.out: vu.bc110201891.btg.Models.CourseModel#21937920
10-05 19:22:05.565 10503-10503/vu.bc110201891.btg I/System.out: aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
10-05 19:22:05.565 10503-10503/vu.bc110201891.btg I/System.out: ttttttttttttttttttttt
10-05 19:22:05.565 10503-10503/vu.bc110201891.btg I/System.out: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
Here:
context = this.context;
context object is null. change this in Constructor as:
this.context = context;
Trying to parse using jackson through intent data and adding to pojo class and getting back but not able to send and fetch ?
MainActivity is..
public class MainActivity extends AppCompatActivity {
private Button getButton;
private TextView textView;
private String jsonData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_json);
super.onCreate(savedInstanceState);
getButton = (Button) findViewById(R.id.getButton);
textView = (TextView) findViewById(R.id.textView);
getButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new JSONTask().execute("http://192.168.11.75/Headspire/api.php");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
private String json_string = "";
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
while ((json_string = reader.readLine()) != null) {
buffer.append(json_string);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
textView.setText(result);
jsonData = result;
}
}
public void parseJSON(View view)
{
if (jsonData == null)
{
Toast.makeText(getApplicationContext(),
"Get JSON data first", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, ActivityListView.class);
intent.putExtra("json_data", jsonData);
startActivity(intent);
}
}
}
Here this is my ActivityListView class...
public class ActivityListView extends AppCompatActivity
{
private String jsonData;
private ListView listView;
private PersonAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_view);
listView = (ListView) findViewById(R.id.listView);
adapter = new PersonAdapter(this, R.layout.row);
listView.setAdapter(adapter);
jsonData = getIntent().getExtras().getString("json_data");
ObjectMapper mapper = new ObjectMapper();
try
{
PersonModel model = mapper.readValue(jsonData, PersonModel.class);
model.getName();
model.getId();
model.getDescription();
model.getRating();
adapter.add(model);
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My PersonAdapeter class looks like this
public class PersonAdapter extends ArrayAdapter
{
private List list = new ArrayList();
public PersonAdapter(Context context, int resource) {
super(context, resource);
}
#SuppressWarnings("unchecked")
public void add(PersonModel object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
row = convertView;
NameHolder nameHolder;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
nameHolder = new NameHolder();
nameHolder.nameTextView = (TextView) row.findViewById(R.id.nameTextView);
nameHolder.idTextView = (TextView) row.findViewById(R.id.idTextView);
nameHolder.descriptionTextView = (TextView) row.findViewById(R.id.descriptionTextView);
nameHolder.ratingTextView = (TextView) row.findViewById(R.id.ratingTextView);
row.setTag(nameHolder);
}
else {
nameHolder = (NameHolder)row.getTag();
}
PersonModel model = (PersonModel) this.getItem(position);
nameHolder.nameTextView.setText(model.getName());
nameHolder.idTextView.setText(model.getId());
nameHolder.descriptionTextView.setText(model.getDescription());
nameHolder.ratingTextView.setText(model.getRating());
return row;
}
static class NameHolder
{
TextView nameTextView, idTextView, descriptionTextView, ratingTextView;
}
}
Here it is my PersonModel class...
#JsonIgnoreProperties(ignoreUnknown=true)
public class PersonModel extends AppCompatActivity
{
private String name;
private String id;
private String description;
private String rating;
public PersonModel(String name, String id, String description,
String rating)
{
this.name = name;
this.id = id;
this.description = description;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
#Override
public String toString()
{
return "PersonModel [name=" + name + ", id=" + id + ",
description=" + description + ", " +
"rating=" + rating +"]";
}
}
I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.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) {
View row=convertView;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,