Ok the app populates the list view from a Url(json). But I want to change the app so that the list view is populated by user input. How do I go about this. Here is my main activity so far:
package ionictech.com.onspot;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import ionictech.com.onspot.adapter.FeedListAdapter;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
public class OnSpotActivity extends ActionBarActivity {
private DrawerLayout drawerLayout;
private String[] Menu;
private static final String TAG = OnSpotActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_spot);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem> ();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable (Color.parseColor ("#ffba00")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getmInstance ().getmRequestQueue ().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d (TAG, "Response: " + response.toString ());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getmInstance ().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And here is my feed item list class:
package ionictech.com.onspot.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import ionictech.com.onspot.FeedImageView;
import ionictech.com.onspot.R;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
/**
* Created by MarcusLee on 9/30/14.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getmInstance ().getImageLoader();
public FeedListAdapter (Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getmInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString (
Long.parseLong (item.getTimeStamp ()),
System.currentTimeMillis (), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty (item.getStatus ())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml ("<a href=\"" + item.getUrl () + "\">"
+ item.getUrl () + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance ());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
I know that the input has to be sent to a server and then read and put into the list view, I just don't know the methods and such. Any help would be most grateful!
Related
I have an activity that fetches content from a JSON URL and displays the contents in a list view.
The contents include images, URL of the post, description etc. Each content item has its own URL.
I want to open it in another activity which has a WebView.
This is MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
private static final String JSON_URL = "https://gist.githubusercontent.com/radiotracer133/f9c5abf2c1fb403c4091ff7bc2ed8845/raw/78b956f078191c3f4b6c2c9c27f92da7ada2f7b4/example.json";
//the tutorial list where we will store all the tutorial objects after parsing json
List<Books> booksList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
booksList = new ArrayList<>();
//this method will fetch and parse the data
loadTutorialList();
}
private void loadTutorialList() {
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named tutorial inside the object
//so here we are getting that json array
JSONArray tutorialsArray = obj.getJSONArray("Books");
//now looping through all the elements of the json array
for (int i = 0; i < tutorialsArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject tutorialsObject = tutorialsArray.getJSONObject(i);
//creating a books object and giving them the values from json object
Books books = new Books(tutorialsObject.getString("Name"), tutorialsObject.getString("image"),tutorialsObject.getString("Author"), tutorialsObject.getString( "Name_url" ));
//adding the books to tutoriallist
booksList.add( books );
}
//creating custom adapter object
MyAdapter adapter = new MyAdapter( booksList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occur
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
This is MyAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends ArrayAdapter<Books> {
//the tutorial list that will be displayed
private List<Books> booksList;
private Bitmap bitmap;
private Context mCtx;
//here we are getting the tutoriallist and context
//so while creating the object of this adapter class we need to give tutoriallist and context
public MyAdapter(List<Books> booksList, Context mCtx) {
super(mCtx, R.layout.list_item, booksList );
this.booksList = booksList;
this.mCtx = mCtx;
}
//this method will return the list item
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the layoutinflater
ViewHolder holder;
LayoutInflater inflater = LayoutInflater.from(mCtx);
convertView = inflater.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
//getting text views
holder.textViewName = convertView.findViewById(R.id.textViewName);
holder.textDescription = convertView.findViewById(R.id.textViewImageUrl);
holder.imageView = convertView.findViewById(R.id.imageView);
holder.detailsView = convertView.findViewById( R.id.detailsview );
convertView.setTag(holder);
//Getting the books for the specified position
Books books = booksList.get(position);
String imageUrl = books.getImageUrl();
String tutorialDescription = books.getDescription();
String tutorialTitle = books.getName();
String detailsTitle = books.getDetails();
holder.textViewName.setText(tutorialTitle);
holder.textDescription.setText(tutorialDescription);
holder.detailsView.setText( detailsTitle );
if (holder.imageView != null) {
/*-------------fatching image------------*/;
new ImageDownloaderTask(holder.imageView).execute(imageUrl);
}
holder.imageView.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
TextView textViewName;
TextView textDescription;
ImageView imageView;
TextView detailsView;
}
}
How can I implement OnclickListerner here to open WebView?
I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(
I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!
A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}
you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode
This is my Json coding
while compiling my code this error pops up org.json.JSONException: End of input at character 0 of and my xml page is displaying empty
Json coding
`
import android.content.Context;
import android.preference.PreferenceManager;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.ram.northmadras.URLs.articleconURL;
import static com.example.ram.northmadras.URLs.articlecon_tag;
class UserFunctions {
private JSONParser jsonParser;
UserFunctions(){
jsonParser = new JSONParser();
}
ArrayList<HashMap<String, String>> getArticlecon(int startIndex){
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("tag", articlecon_tag));
params.add(new BasicNameValuePair("index",""+startIndex));
ArrayList<HashMap<String, String>> arrayList=new ArrayList<>();
JSONObject jsonObject= jsonParser.getJSONFromUrl(articleconURL, params);
try {
for (int i = 0; i < jsonObject.getInt("max"); i++) {
HashMap<String, String> hashMap = new HashMap<>();
String json = jsonObject.getString("" + (i));
json = json.replace("[", "");
json = json.replace("]", "");
JSONObject jsonObject1 = new JSONObject(json);
hashMap.put("Title", jsonObject1.getString("Title"));
hashMap.put("Description", jsonObject1.getString("Description"));
hashMap.put("Image", jsonObject1.getString("Image"));
hashMap.put("PostedTime", jsonObject1.getString("PostedTime"));
hashMap.put("PostedByName", jsonObject1.getString("postedByName"));
arrayList.add(hashMap);
}
}catch (Exception ignored){}
return arrayList;
}
` }
This is my Json string.
this is an php file
articlecon.php
<?php
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
$tag = $_POST['tag'];
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("tag" => $tag, "success" => 0, "error" => 0);
if ($tag == 'getarticlecon')
{
$users = $db->getarticlecon($_POST['index']);
if ($users != false)
{
$c=1;
while ($user=mysql_fetch_assoc($users)) {
$response[][]=$user;
$c++;
}
$response["success"]=1;
$response["max"]=$c;
$response["itemsCount"]=7;
echo json_encode($response);
} else {
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
}
?>
DB_Functions.php
public function getarticlecon($index)
{
$result = mysql_query("SELECT Title,Description,Image,PostedTime,PostedByName FROM articles LIMIT 10 OFFSET $index ") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
//$result = mysql_fetch_assoc($result);
return $result;
} else {
// user not found
return false;
}
}
I using two java classes ArticleContent and CustomArticle Adapter
These are my java_classes
ArticleContent.java
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ArticleContent extends AppCompatActivity
{
TextView textView;
ImageView imageview;
static CustomArticleAdapter adapter;
static int startIndex;
ArrayList<HashMap<String, String>> arrayList;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article_content);
textView = (TextView) findViewById(R.id.textview1);
textView = (TextView) findViewById(R.id.textview2);
textView = (TextView) findViewById(R.id.textview3);
textView = (TextView) findViewById(R.id.textview4);
imageview = (ImageView) findViewById((R.id.img1));
arrayList = new ArrayList<>();
new ArticleContent.json(startIndex).execute();
startIndex += 10;
int[] ids = {R.id.textview1, R.id.textview2, R.id.textview3, R.id.textview4, R.id.img1};
String[] keys = {"Title", "Description", "PostedTime", "PostedByName", "Image"};
//adapter = new SimpleAdapter(ArticleContent.this, arrayList, R.layout.article_content, keys, ids);
adapter=new CustomArticleAdapter(this,arrayList);
// listView.setAdapter(adapter);
}
#SuppressLint("StaticFieldLeak")
class json extends AsyncTask<Void,Void,ArrayList<HashMap<String,String>>> {
ProgressDialog pDialog;
int startIndex;
public json(int startIndex) {
this.startIndex=startIndex;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ArticleContent.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... voids) {
UserFunctions userFunction = new UserFunctions();
arrayList.addAll(userFunction.getArticlecon(startIndex));
try
{
} catch (Exception e) {
Log.e("aaa123456",arrayList.toString());
}
return arrayList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
try {
adapter.notifyDataSetChanged();
pDialog.dismiss();
} catch (Exception e) {
Log.e("aaa7890123456",arrayList.toString());
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
}
}
}
This is an custom adapter class
CustomArticleAdapter.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Ram on 2/23/2018.
*/
public class CustomArticleAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, String>> article;
LayoutInflater layoutInflater;
public CustomArticleAdapter(Context context, ArrayList<HashMap<String, String>> article) {
this.context = context;
this.article = article;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return article.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView textviewa, textviewb, textviewc, textviewd;
ImageView imgs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = (View) layoutInflater.inflate(R.layout.article_content, null);
holder.textviewa = (TextView) convertView.findViewById(R.id.textview1);
holder.textviewb = (TextView) convertView.findViewById(R.id.textview2);
holder.textviewc = (TextView) convertView.findViewById(R.id.textview3);
holder.textviewd = (TextView) convertView.findViewById(R.id.textview4);
holder.imgs = (ImageView) convertView.findViewById(R.id.img1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textviewa.setText(article.get(position).get("Title"));
holder.textviewb.setText(article.get(position).get("Description"));
holder.textviewc.setText(article.get(position).get("PostedTime"));
holder.textviewd.setText(article.get(position).get("PostedByName"));
Picasso.with(context).load("http://www.northmadras.com/upload/Articles/"+article.get(position).get("Image")).into(holder.imgs);
holder.imgs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context,ArticleContent.class);
String keyIdentifer = null;
i.putExtra("Title", keyIdentifer );
i.putExtra("Description", keyIdentifer );
i.putExtra("PostedTime", keyIdentifer );
i.putExtra("PostedByName", keyIdentifer );
i.putExtra("image", keyIdentifer );
}
});
return convertView;
}
}
My program is designed to search the database for the specific name entered, then the program will only display the row of the specific name. However, my code is unable to display the specific data. I have tried many kind of ways but it is unable to solve my problem. My php code is as below:
<?php
$con = mysql_connect('mysql17.000webhost.com', 'a2634311_minzhe', 'MZRules0118');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2634311_gdp", $con);
$result = mysql_query("SELECT * FROM groupdesign");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
My activity code is as below:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
public class PatientLocation extends ActionBarActivity {
private ListView PatientLocationListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.PatientLocationListView = (ListView) this.findViewById(R.id.listView4);
new Location().execute(new API_Connector());
}
public void setListAdapter(JSONArray jsonArray) {
SharedPreferences settings = getSharedPreferences("myprefrences", Context.MODE_PRIVATE);
String name = settings.getString("name", "");
this.PatientLocationListView.setAdapter(new PatientAdapter(jsonArray,name, this));
}
private class Location extends AsyncTask<API_Connector, Long, JSONArray> {
#Override
protected JSONArray doInBackground(API_Connector... params) {
//it is executed on Background thread
return params[0].GetPatientLocation();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
// check for null
if (jsonArray != null) {
// only pass the array to adapter if it is not null
setListAdapter(jsonArray);
} else {
Toast.makeText(PatientLocation.this, "Null Array returned", Toast.LENGTH_SHORT).show();
}
}
}
}
class PatientAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
String pname;
private static LayoutInflater inflater = null;
public PatientAdapter(JSONArray jsonArray, String name, Activity a) {
this.dataArray = jsonArray;
this.activity = a;
this.pname = name;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String patientname,patientlocation;
//set up convert view if it is null
ListCell cell = new ListCell();
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_position, null);
cell.patient_name = (TextView) convertView.findViewById(R.id.textView30);
cell.patient_location = (TextView) convertView.findViewById(R.id.textView31);
convertView.setTag(cell);
}
else {
cell = (ListCell) convertView.getTag();
}
//change the data of the cell
try {
for(int i=0;i<dataArray.length();i++) {
JSONObject jsonObject = this.dataArray.getJSONObject(i);
if(pname == jsonObject.getString("Name")) {
patientname = jsonObject.getString("Name");
patientlocation = jsonObject.getString("Location");
cell.patient_name.setText(patientname);
cell.patient_location.setText(patientlocation);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView patient_name;
private TextView patient_location;
}
}
Where is WHERE clause in your query in php code? You need to set some conditions to match specific name in query like if you want to search 'abcd' then your query should be SELECT * FROM groupdesign WHERE column_name = "abcd". This will return records which contanis value "abcd" from your database