Populating TextView after Spinner Selection - java

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

Related

JSON Volley Nested JSON Array com.android.volley.ParseError: org.json.JSONException

I wanna getJudul(), getExcerpt(), and getPostImg() from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But it show me com.android.volley.ParseError: org.json.JSONException
Below the code you can check...
DaftarCategories
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) {
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
for(int c=0; c<postCategoryObj.length(); c++) {
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(c);
String postCategoryUrl = postCategoryIndex.getString("href");
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonObjectRequest getKonten = new JsonObjectRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
// Get category title
JSONObject titleObj = response.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get category excerpt
JSONObject exerptObj = response.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get category content
JSONObject contentObj = response.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
//////////////////////////////////////////////////////////////////////////////////////
// getting URL of the Post fetured Image
JSONObject featureImage = response.getJSONObject("_links");
JSONArray featureImageUrl = featureImage.getJSONArray("wp:featuredmedia");
for(int y=0; y<featureImageUrl.length(); y++){
JSONObject featureImageObj = featureImageUrl.getJSONObject(y);
String fiurl = featureImageObj.getString("href");
if(fiurl != null) {
Log.d(TAG, featureImageObj.getString("href"));
JsonObjectRequest getMedia = new JsonObjectRequest(Request.Method.GET, fiurl, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONObject exerptObj = response.getJSONObject("guid");
post.setPostImg(exerptObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
//notifyDataSetChanged untuk mendapatkan gambar
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getMedia);
} //if fiurl
} //for image url
} //try 2
catch (JSONException e) {
e.printStackTrace();
}
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
} //for postCategory
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
gambar = click.getPostImg();
judul = click.getJudul();
url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("excerpt", excerpt);
bundle.putString("gambar", gambar);
bundle.putString("judul", judul);
bundle.putString("url", url);
bundle.putString("content", content);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory
public class PostsBasedOnCategory extends Fragment implements AdapterCategoryPosts.PostingAdapterListener {
public static PostsBasedOnCategory newInstance()
{
return new PostsBasedOnCategory();
}
private RecyclerView recycleViewWordPress;
private AdapterCategoryPosts mAdapter;
private RequestQueue queue;
public ArrayList<CategoriesModel> typeForPosts;
private SwipeRefreshLayout swipeRefreshLayout;
private ProgressBar pb;
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
public static String TAG = "postFrag";
private int index;
private TextView noFavtsTV;
private SearchView searchView;
private String content, gambar, judul, url;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
Bundle bundel = this.getArguments();
if(bundel != null){
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel post = new CategoriesModel();
post.setJudul(title);
post.setExcerpt(excerpt);
post.setPostImg(pict);
post.setPostURL(url);
post.setContent(konten);
typeForPosts = new ArrayList<CategoriesModel>();
typeForPosts.add(post);
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
pb.setVisibility(View.VISIBLE);
}
else {
pb.setVisibility(View.GONE);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
}
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
content = click.getContent();
gambar = click.getPostImg();
judul = click.getJudul();
url = click.getPostURL();
Intent fullScreenIntent = new Intent(getContext(), DetailCategoryPost.class);
fullScreenIntent.putExtra("content", content);
fullScreenIntent.putExtra("gambar", gambar);
fullScreenIntent.putExtra("judul", judul);
fullScreenIntent.putExtra("url", url);
startActivity(fullScreenIntent);
}
private void showNoFav(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recycleViewWordPress.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_search, menu);
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return true;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return true;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
#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.action_search) {
return true;
}
//Menu
if (id == R.id.action_settings) {
//startActivity(new Intent(this, SettingsActivity.class));
//return true;
}
else
if (id == R.id.about_us) {
//startActivity(new Intent(this, AboutUs.class));
//return true;
}
return super.onOptionsItemSelected(item);
}
}
AdapterCategoryPosts
public class AdapterCategoryPosts extends RecyclerView.Adapter<AdapterCategoryPosts.ViewHolder> implements Filterable {
private Context context;
private List<CategoriesModel> typeForPosts;
private List<CategoriesModel> typeForPostsFiltered;
private PostingAdapterListener listener;
public AdapterCategoryPosts(Context context, List<CategoriesModel> typeForPosts, PostingAdapterListener listener) {
this.context = context;
this.typeForPosts = typeForPosts;
this.typeForPostsFiltered = typeForPosts;
this.listener = listener;
}
public interface PostingAdapterListener {
void onPostingSelected(int pos);
}
#Override
public AdapterCategoryPosts.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.postitem, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tempelData(typeForPosts.get(position), holder.getAdapterPosition());
holder.viewCari(typeForPostsFiltered.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return typeForPostsFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
typeForPostsFiltered = typeForPosts;
}
else {
List<CategoriesModel> filteredList = new ArrayList<>();
for (CategoriesModel row : typeForPosts) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getJudul().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
typeForPostsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = typeForPostsFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
typeForPostsFiltered = (ArrayList<CategoriesModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
TextView title, excerpt;
ImageView blog_image;
private String TAG = "LoadImage";
public ViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
excerpt = (TextView) v.findViewById(R.id.excerpt);
blog_image = (ImageView) v.findViewById(R.id.blog_image);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
if (listener != null){
int position = getAdapterPosition();
String name = typeForPostsFiltered.get(position).getJudul();
for (int i=0; i<typeForPosts.size(); i++){
if( name.equals(typeForPosts.get(i).getJudul()) ){
position = i;
break;
}
}
if(position != RecyclerView.NO_POSITION) {
listener.onPostingSelected(position);
}
}
}
});
}
public void tempelData(final CategoriesModel item, final int adapterPosition) {
String judulx = item.getJudul();
if(judulx != null){
title.setText(Html.fromHtml(item.getJudul()));
}
String desk = item.getExcerpt();
if(desk != null){
if(desk.length() >= 254){
excerpt.setText(Html.fromHtml(desk.substring(0, 254)));
}
else {
excerpt.setText(Html.fromHtml(item.getExcerpt()));
}
}
Glide.with(context).load(item.getPostImg()).thumbnail(0.2f).apply(fitCenterTransform()).thumbnail(0.2f).apply(fitCenterTransform()).into(blog_image);
} // tempeldata
public void viewCari(final CategoriesModel stori, final int adapterPosition) {
final CategoriesModel posting = typeForPostsFiltered.get(adapterPosition);
title.setText(posting.getJudul());
Glide.with(context).load(posting.getPostImg()).into(blog_image);
} //viewCari
}
}
SumberPosts
public class SumberPosts {
public static String HOST="192.168.1.100";
public static String HOST_URL="https://www.kisahmuslim.com/wp-json/";
public static String AMP="amp/";
public static String CHECK_URL="http://localhost/";
public static String REPLACE_URL="http://"+HOST.trim()+"/";
public static String TEMPLATE_FOR_TIME = "yyyy-MM-dd";
public static String RESPONSE = "for_post";
public static String RESPONSE_1 = "id";
public static String RESPONSE_2 = "name";
public static String RESPONSE_3 = "link";
public static String RESPONSE_4 = "time";
public static String RESPONSE_5 = "content";
public static String RESPONSE_6 = "author";
public static String RESPONSE_7 = "image";
public static String RESPONSE_8 = "category";
}
Add dependencies as follows:
implementation 'com.google.code.gson:gson:2.8.5'
Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true.
Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.
Change your code from
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true)
to
// open http connection
conn = (HttpURLConnection) new URL(url).openConnection();
// http method
conn.setRequestMethod("GET");
// enable read mode (always)
conn.setDoInput(true);
// disable write (for GET, HEAD, OPTIONS, TRACE)
conn.setDoOutput(false);
and
protected void onPostExecute(String result)
{
if ((result.startsWith("{") || result.startsWith("["))) {
// JSON output
JsonArray arr = gson.fromJson(content, (Type) JsonArray.class);
if (arr != null) {
for (int i = 0; i < arr.size(); i++) {
JsonObject obj = (JsonObject) arr.get(i);
if (obj != null) {
Log.i("TAG_:", "\n\n------------------------------------{ " + (i + 1) + " }");
if (obj.has("id")) {
Log.i("TAG_id:", obj.get("id").getAsString());
}
if (obj.has("count")) {
Log.i("TAG_count:", obj.get("count").getAsString());
}
if (obj.has("description")) {
Log.i("TAG_description:", obj.get("description").getAsString());
}
if (obj.has("link")) {
Log.i("TAG_link:", obj.get("link").getAsString());
}
if (obj.has("name")) {
Log.i("TAG_name:", obj.get("name").getAsString());
}
if (obj.has("slug")) {
Log.i("TAG_slug:", obj.get("slug").getAsString());
}
if (obj.has("taxonomy")) {
Log.i("TAG_taxonomy:", obj.get("taxonomy").getAsString());
}
if (obj.has("parent")) {
Log.i("TAG_parent:", obj.get("parent").getAsString());
}
if (obj.has("meta")) {
JsonArray arr1 = obj.get("meta").getAsJsonArray();
if (arr1 != null) {
for (int j = 0; j < arr1.size(); j++) {
JsonObject obj1 = (JsonObject) arr1.get(j);
if (obj1 != null) {
Log.i("TAG_meta:", obj1.get("").getAsString());
}
}
}
}
if (obj.has("_links")) {
JsonObject obj2 = obj.get("_links").getAsJsonObject();
if (obj2 != null) {
if (obj2.has("self")) {
JsonArray arr2 = obj2.get("self").getAsJsonArray();
if (arr2 != null) {
for (int j = 0; j < arr2.size(); j++) {
JsonObject obj3 = arr2.get(j).getAsJsonObject();
if (obj3 != null) {
Log.i("TAG_self_href:", obj3.get("href").getAsString());
}
}
}
}
if (obj2.has("collection")) {
JsonArray arr3 = obj2.get("collection").getAsJsonArray();
if (arr3 != null) {
for (int j = 0; j < arr3.size(); j++) {
JsonObject obj4 = arr3.get(j).getAsJsonObject();
if (obj4 != null) {
Log.i("TAG_collection_href:", obj4.get("href").getAsString());
}
}
}
}
if (obj2.has("about")) {
JsonArray arr4 = obj2.get("about").getAsJsonArray();
if (arr4 != null) {
for (int j = 0; j < arr4.size(); j++) {
JsonObject obj5 = arr4.get(j).getAsJsonObject();
if (obj5 != null) {
Log.i("TAG_about_href:", obj5.get("href").getAsString());
}
}
}
}
if (obj2.has("up")) {
JsonArray arr5 = obj2.get("up").getAsJsonArray();
if (arr5 != null) {
for (int j = 0; j < arr5.size(); j++) {
JsonObject obj6 = arr5.get(j).getAsJsonObject();
if (obj6 != null) {
Log.i("TAG_up_embeddable:", obj6.get("embeddable").getAsString());
Log.i("TAG_up_href:", obj6.get("href").getAsString());
}
}
}
}
if (obj2.has("wp:post_type")) {
JsonArray arr6 = obj2.get("wp:post_type").getAsJsonArray();
if (arr6 != null) {
for (int j = 0; j < arr6.size(); j++) {
JsonObject obj7 = arr6.get(j).getAsJsonObject();
if (obj7 != null) {
Log.i("TAG_wp:post_type_href:", obj7.get("href").getAsString());
}
}
}
}
if (obj2.has("curies")) {
JsonArray arr7 = obj2.get("curies").getAsJsonArray();
if (arr7 != null) {
for (int j = 0; j < arr7.size(); j++) {
JsonObject obj8 = arr7.get(j).getAsJsonObject();
if (obj8 != null) {
Log.i("TAG_curies_name:", obj8.get("name").getAsString());
Log.i("TAG_curies_href:", obj8.get("href").getAsString());
Log.i("TAG_curies_templated:", obj8.get("templated").getAsString());
}
}
}
}
}
}
}
}
}
}
}
result:
TAG_:: ------------------------------------{ 1 }
TAG_id:: 12
TAG_count:: 57
TAG_link:: https://kisahmuslim.com/category/kisah-nyata/biografi-ulama
TAG_name:: Biografi Ulama
TAG_slug:: biografi-ulama
TAG_taxonomy:: category
TAG_parent:: 29
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/12
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_up_embeddable:: true
TAG_up_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/29
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true
TAG_:: ------------------------------------{ 2 }
TAG_id:: 26
TAG_count:: 8
TAG_link:: https://kisahmuslim.com/category/download
TAG_name:: Download
TAG_slug:: download
TAG_taxonomy:: category
TAG_parent:: 0
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/26
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=26
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true
// saya sengaja tidak tampilkan semua disini untuk menghemat ruang.
TAG_:: ------------------------------------{ 10 }
TAG_id:: 29
TAG_count:: 255
TAG_link:: https://kisahmuslim.com/category/kisah-nyata
TAG_name:: Kisah Nyata
TAG_slug:: kisah-nyata
TAG_taxonomy:: category
TAG_parent:: 0
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/29
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=29
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true

How to send values from an arraylist from AsyncTask class to another class in Android?

I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}

RecyclerView: No adapter attached; skipping layout when Im running

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

How to get a single column in android mysql

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.

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

Categories