I am trying to fill an alert dialog with a JSON response how ever i am getting the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
i have inflated the list view in the onCreate as other posts suggest
i have included all relevant xml and java code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckedTextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
public class QueueStatusFragment extends Fragment{
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private TextView txtQueue;
private TextView txtCust;
private TextView txtTime;
private TextView txtBranch;
private String urlString;
private Button btnLeave;
private int reasonId;
ListView list;
public QueueStatusFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_queuestatus, container, false);
txtQueue = (TextView) v.findViewById(R.id.txtQueue);
txtTime = (TextView) v.findViewById(R.id.txtTime);
txtCust = (TextView) v.findViewById(R.id.txtCust);
txtBranch = (TextView) v.findViewById(R.id.txtBranch);
list=(ListView)v.findViewById(R.id.listviewResp);
btnLeave = (Button) v.findViewById(R.id.btnLeave);
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/queueDetails/" + globalVariable.getCustId();
new ProcessJson().execute(urlString);
System.out.println("works");
btnLeave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
for(int i = 0; i < oslist.size();i++)
{
String id = oslist.get(i).get("id");
System.out.println(id);
}
}
});
alertDialog.show();
// SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
//String urlString1 = "http://172.20.10.5:1012/easyQ.svc/rest/leaveQueue";
// new JsonHandler().execute(urlString1);
//System.out.println("works");
}
});
// Inflate the layout for this fragment
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private class ProcessJson extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
String[] array = stream.split(",");
String part1 = array[1];
String part2 = array[2];
String part3 = array[3];
String part4 = array[4];
String queueId = array[5];
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setQueueId(queueId);
if (part1 != null && part2 != null && part3 != null) {
int minutes = (int) Integer.parseInt(part1) / 60;
txtBranch.append("Branch Name: " + part4);
txtQueue.append("Service Name: " + part3);
txtCust.append("Queue Position: " + part2);
txtTime.append("Waiting Time: " + minutes + " minutes");
}
}
}
}
private class getReasons extends AsyncTask<String, Void, String>{
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.text1});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new JoinFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
private class JsonHandler extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
System.out.println("sssss" + globalVariable.getQueueId() + globalVariable.getCustId());
JSONObject sender = new JSONObject();
try {
sender.put("queueid", globalVariable.getQueueId());
sender.put("customerid", globalVariable.getCustId());
//sender.put("reasonid",);
} catch (JSONException e) {
e.printStackTrace();
}
stream = hh.POST(urlString, sender);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
if (stream.equals("\"Successful\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Successfully left Queue", Toast.LENGTH_LONG).show();
Fragment fragment=null;
fragment=new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
} else if (stream.equals("\"Not Exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Unable to leave Queue", Toast.LENGTH_LONG).show();
} else if (stream.equals("\"Not exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Not in queue", Toast.LENGTH_LONG).show();
}
}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment" >
<TextView
android:id="#+id/txtBranch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="hello"
android:layout_marginTop="100dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtQueue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello1"
android:layout_marginTop="160dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello2"
android:gravity="center|left"
android:layout_marginTop="44dp"
android:layout_centerInParent="false"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtQueue"
android:layout_alignStart="#+id/txtQueue" />
<TextView
android:id="#+id/txtCust"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello3"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_marginTop="47dp"
android:layout_centerInParent="false"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtTime"
android:layout_alignStart="#+id/txtTime" />
<Button
android:id="#+id/btnLeave"
android:layout_width="312dp"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:gravity="center"
android:text="Leave Queue"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginBottom="65dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I think your problem is in your fragment_queuestatus there is no Listview. Which you add the previous layout. That why it's not get the listview and when you try to set the adapter it's thing you set something in a NULL object. So, Add the ListView in the fragment_queuestatus layout. That will solve the problem.
Related
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
I am getting the following error: "RecyclerView: No adapter attached; skipping layout" but I have attached the adapter... I have tried many different ways but I couldn't solve the error.
I am using Volley library to get data. When I launch the activity, only the progress bar is visible until the end, and I receive the Logcat message above. I have added the Recycleview with the adapter in the MainActivity. Could you please help me?
Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private RequestQueue mRequestQueue;
private ArrayList<Earthquake> mEarthquake;
private RecyclerView mRecycleView;
private EarthquakeAdapter adapter;
boolean isConnected;
TextView emptyView;
ProgressBar loadingIndicator;
private static final String USS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
Read_network_state(cm);
loadingIndicator = findViewById(R.id.loading_indicator);
emptyView = findViewById(R.id.empty_view);
mRecycleView = this.findViewById(R.id.recycle_list);
mRecycleView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecycleView.setLayoutManager(manager);
mEarthquake = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
if (isConnected) {
Uri uri = Uri.parse(USS_REQUEST_URL);
Uri.Builder buider = uri.buildUpon();
parseEarthquake(buider.toString());
}
}
private void parseEarthquake(String key) {
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, key.toString(), null, response -> {
double magnitude = Double.parseDouble("");
String location = "";
long time = Long.parseLong("");
String url = "";
try {
JSONArray feature = response.getJSONArray("feature");
for (int i = 0; i < feature.length(); i++) {
JSONObject features = feature.getJSONObject(i);
JSONObject properties = features.getJSONObject("properties");
magnitude = properties.getDouble("mag");
location = properties.getString("place");
time = properties.getLong("time");
url = properties.getString("url");
}
Earthquake earthquake = new Earthquake(magnitude, location, time, url);
mEarthquake.add(earthquake);
adapter = new EarthquakeAdapter(MainActivity.this, mEarthquake);
mRecycleView.setAdapter(adapter);
Log.d("Ruhul", "No adapter");
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
// Nothing
});
mRequestQueue.add(request);
}
public void Read_network_state(ConnectivityManager connectivityManager) {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
isConnected = true;
Log.d("Ruhul", "CONNECTED TO INTERNET");
} else {
isConnected = false;
}
}
}
EarthquakeAdapter
public class EarthquakeAdapter extends RecyclerView.Adapter<EarthquakeAdapter.MyViewHolder> {
private Context mContext;
private List<Earthquake> mData;
public EarthquakeAdapter(Context mContext, List<Earthquake> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.earthquake_raw, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
Earthquake earthquake = mData.get(i);
double earthquakeMagnitude = earthquake.getMagnitude();
DecimalFormat decimalFormat = new DecimalFormat("0.0");
String formattedMagnitude = decimalFormat.format(earthquakeMagnitude);
holder.tvMagnitude.setText(formattedMagnitude);
Date dateObject = new Date(earthquake.getTimeInMilliseconds());
String formattedDate = formatDate(dateObject);
holder.tvDate.setText(formattedDate);
String formattedTime = formatTime(dateObject);
holder.tvTime.setText(formattedTime);
String originalLocation = earthquake.getLocation();
holder.magnitudeCircle = (GradientDrawable) holder.tvMagnitude.getBackground();
int magnitudecolor = getMagnitudeColor(earthquake.getMagnitude());
holder.magnitudeCircle.setColor(magnitudecolor);
if (originalLocation.contains("of")) {
String[] parts = originalLocation.split("of");
holder.tvLocationOffSet.setText(parts[0] + "of");
holder.tvPrimaryLocation.setText(parts[1]);
} else {
holder.tvLocationOffSet.setText("Near The");
holder.tvPrimaryLocation.setText(originalLocation);
}
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvMagnitude, tvLocationOffSet, tvPrimaryLocation, tvDate, tvTime;
LinearLayout container;
GradientDrawable magnitudeCircle;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvMagnitude = itemView.findViewById(R.id.magnitude);
tvLocationOffSet = itemView.findViewById(R.id.location_offset);
tvPrimaryLocation = itemView.findViewById(R.id.primary_location);
tvDate = itemView.findViewById(R.id.date);
tvTime = itemView.findViewById(R.id.time);
container = itemView.findViewById(R.id.container);
}
}
/**
* Return the color of the magitude circle based on the intensity of the earthquake.
*
* #param magnitude of the earthquake
*/
private int getMagnitudeColor(double magnitude) {
int magnitudeColorResourceId;
int magnitudeFloor = (int) Math.floor(magnitude);
switch (magnitudeFloor) {
case 0:
case 1:
magnitudeColorResourceId = R.color.magnitude1;
break;
case 2:
magnitudeColorResourceId = R.color.magnitude2;
break;
case 3:
magnitudeColorResourceId = R.color.magnitude3;
break;
case 4:
magnitudeColorResourceId = R.color.magnitude4;
break;
case 5:
magnitudeColorResourceId = R.color.magnitude5;
break;
case 6:
magnitudeColorResourceId = R.color.magnitude6;
break;
case 7:
magnitudeColorResourceId = R.color.magnitude7;
break;
case 8:
magnitudeColorResourceId = R.color.magnitude8;
break;
case 9:
magnitudeColorResourceId = R.color.magnitude9;
break;
default:
magnitudeColorResourceId = R.color.magnitude10plus;
break;
}
return ContextCompat.getColor(mContext, magnitudeColorResourceId);
}
private String formatDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
return dateFormat.format(dateObject);
}
private String formatTime(Date dateObject) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
return timeFormat.format(dateObject);
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAppearance="?android:textAppearanceMedium"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycle_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:listitem="#layout/earthquake_raw"/>
<ProgressBar
android:id="#+id/loading_indicator"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
EarthquakeRaw.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="horizontal"
android:paddingStart="16dp"
android:paddingLeft="16dp"
android:paddingEnd="16dp"
android:paddingRight="16dp">
<TextView
android:id="#+id/magnitude"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center_vertical"
android:background="#drawable/magnitude_circle"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:textColor="#android:color/black"
android:textSize="16sp"
tools:text="8.9" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/location_offset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:maxLines="1"
android:textAllCaps="true"
android:textColor="#android:color/black"
android:textSize="12sp"
tools:text="30km S of" />
<TextView
android:id="#+id/primary_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:textColor="#android:color/black"
android:textSize="12sp"
tools:text="Long placeholder that should wrap to more than 2 line of text" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:textColor="#color/textColorEarthquakeDetails"
android:textSize="12sp"
tools:text="Mar 6, 2010" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:textColor="#color/textColorEarthquakeDetails"
android:textSize="12sp"
tools:text="3:00 PM" />
</LinearLayout>
</LinearLayout>
Always try to attach the adapter in main UI thread, or outside your asynchronous task.
Also, you can add this code in oncreate(). and when mEarthquake arraylist is populated, call adapter.notifydatasetchanged().
adapter = new EarthquakeAdapter(MainActivity.this, mEarthquake);
mRecycleView.setAdapter(adapter);
You should add data to model inside for loop.
Try like below will work fine,
JSONArray feature = response.getJSONArray("feature");
for (int i = 0; i < feature.length(); i++) {
JSONObject features = feature.getJSONObject(i);
JSONObject properties = features.getJSONObject("properties");
magnitude = properties.getDouble("mag");
location = properties.getString("place");
time = properties.getLong("time");
url = properties.getString("url");
Earthquake earthquake = new Earthquake(magnitude, location, time, url);
mEarthquake.add(earthquake);
adapter = new EarthquakeAdapter(MainActivity.this, mEarthquake);
mRecycleView.setAdapter(adapter);
adapter.notifyDatasetChanged();
}
I'm trying to cast a database into a ListView, and when tapped on, for it to reveal more information, but I started getting the error in the title once I added the expandable functionality.
Here's my list_item.xml, seemingly the source of the problems:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent"/>
<View
android:layout_width="0px"
android:layout_height="0px"
android:id="#+id/expandable">
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
<TextView
android:id="#+id/telephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
</View>
</LinearLayout>
And here's MainActivity2.java (temp name):
public class MainActivity2 extends Activity {
private String TAG = MainActivity2.class.getSimpleName();
private ListView lv;
private View ex;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
ex = findViewById(R.id.expandable);
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView parentView, View childView,
int position, long id)
{
expand(ex);
}
public void onNothingSelected(AdapterView parentView) {
}
});
}
public static void expand(final View v) {
v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a = new Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LinearLayout.LayoutParams.WRAP_CONTENT
: (int)(targetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity2.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("work");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String telephone = c.getString("telephone");
// Phone node is JSON Object
String description = c.getString("description");
String agerange = c.getString("agerange");
String county = c.getString("county");
String category = c.getString("category");
String website = c.getString("website");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("description", description);
contact.put("name", name);
contact.put("email", email);
contact.put("telephone", telephone);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity2.this, contactList,
R.layout.list_item, new String[]{ "email","description","name"},
new int[]{R.id.email, R.id.description, R.id.name});
lv.setAdapter(adapter);
}
}
}
If any more information is needed, I will happily provide it.
Thank You in advance
EDIT:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.teamplum.projectapple, PID: 12076
java.lang.ClassCastException: android.view.View cannot be cast to android.view.ViewGroup
at android.view.LayoutInflater.rInflate(LayoutInflater.java:826)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:523)
at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:121)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:2481)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1289)
at android.widget.ListView.onMeasure(ListView.java:1197)
at android.view.View.measure(View.java:17970)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:816)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:561)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:785)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:654)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2755)
at android.view.View.measure(View.java:17970)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2438)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1418)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1642)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1296)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6742)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:826)
at android.view.Choreographer.doCallbacks(Choreographer.java:629)
at android.view.Choreographer.doFrame(Choreographer.java:597)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:812)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5931)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:987)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)
this error says that you are putting views inside <View>. change this view to a ViewGroup (e.g linearLayout or RelativeLayout ) and your problem will disappear.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" <!-- edit this height and width-->
<!--also add orientation-->
android:id="#+id/expandable">
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
<TextView
android:id="#+id/telephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
I have a RecyclerView which items I populate from json response.
public class UserProfile extends AppCompatActivity {
private UserData userData;
private ProfileNewsFeedAdapter adapter;
private ArrayList<ProgramModel> list;
private RecyclerView profileNewsFeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
userData = new UserData(this);
list = new ArrayList<>();
adapter = new ProfileNewsFeedAdapter(getActivity(), list);
initializeViews();
}
private void initializeViews() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle(userData.getName());
TextView userEmail = (TextView) findViewById(R.id.emailPrfId);
TextView birthday = (TextView) findViewById(R.id.birthdayId);
TextView userClass = (TextView) findViewById(R.id.userClassId);
userEmail.setText(userData.getEmail());
birthday.setText("Ditëlindja: " + userData.getBirthday());
userClass.setText("Klasa: " + userData.getUserClass());
setFont(userEmail);
setFont(birthday);
setFont(userClass);
profileNewsFeed = (RecyclerView) findViewById(R.id.profileNewsFeed);
profileNewsFeed.setLayoutManager(new LinearLayoutManager(this));
profileNewsFeed.setItemAnimator(new DefaultItemAnimator());
profileNewsFeed.setHasFixedSize(true);
profileNewsFeed.setAdapter(adapter);
GetBorrowedBooks getBorrowedBooks = new GetBorrowedBooks();
getBorrowedBooks.execute();
}
private void setFont(TextView textView) {
textView.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"));
}
private AppCompatActivity getActivity() {
return this;
}
private class GetBorrowedBooks extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String userId = userData.getUserId();
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/user/" + userId + "/requests", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imageName = "http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/files/books/" + jsonObject.getString("cover");
list.add(new ProgramModel(jsonObject.getString("title"), jsonObject.getString("author"), imageName));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MyDynamicToast.errorMessage(AppController.getInstance(), "Volley did not respond!");
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
return null;
}
}
}
This is the adapter code:
public class ProfileNewsFeedAdapter extends RecyclerView.Adapter<ProfileNewsFeedAdapter.MyViewHolder> {
private AppCompatActivity activity;
private ArrayList<ProgramModel> program;
private LayoutInflater inflater;
public ProfileNewsFeedAdapter(AppCompatActivity activity, ArrayList<ProgramModel> program) {
this.activity = activity;
inflater = activity.getLayoutInflater();
this.program = program;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, author;
ImageView bookImage;
MyViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.bookTitleBorrowId);
author = (TextView) v.findViewById(R.id.bookAuthorBorrowId);
bookImage = (ImageView) v.findViewById(R.id.bookImageBorrowCardId);
}
void setMenuDetail(ProgramModel model, final int position) {
title.setText(model.getTitle());
author.setText(model.getMessage());
// Set text fonts
title.setTypeface(Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Bold.ttf"));
author.setTypeface(Typeface.createFromAsset(activity.getAssets(), "fonts/Roboto-Light.ttf"));
Picasso.with(activity).load(model.getImageUrl()).into(bookImage);
bookImage.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bookImageCardId:
new GetBookInfo(activity, title.getText().toString()).execute();
break;
}
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.profile_cardview_item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ProgramModel menuModel = program.get(position);
holder.setMenuDetail(menuModel, position);
}
#Override
public int getItemCount() {
return program.size();
}
private class GetBookInfo extends AsyncTask<Void, Void, Void> {
private String bookTitle, bookAuthor, bookDescription, requestedBook, bookUrl, bookId;
private int copies;
private Context c;
GetBookInfo(Context c, String requestedBook) {
this.c = c;
this.requestedBook = requestedBook;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
fetchBookInfo();
return null;
}
private void fetchBookInfo() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, AppConfig.URL_FETCH_BOOKS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getString("title").equals(requestedBook)) {
bookId = "" + jsonObject.getInt("id");
bookTitle = jsonObject.getString("title");
bookAuthor = jsonObject.getString("author");
bookDescription = jsonObject.getString("description");
copies = jsonObject.getInt("quantity");
setBookUrl("http://ec2-52-39-232-168.us-west-2.compute.amazonaws.com/files/books/" + jsonObject.getString("cover"));
Intent intent = new Intent(c, BookActivity.class);
intent.putExtra("title", getBookTitle());
intent.putExtra("author", getBookAuthor());
intent.putExtra("bookId", getBookId());
intent.putExtra("description", getBookDescription());
intent.putExtra("copies", getCopies());
intent.putExtra("description", getBookDescription());
intent.putExtra("bookUrl", getBookUrl());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Error: ", "" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MyDynamicToast.errorMessage(AppController.getInstance(), "Volley Error!");
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
}
String getBookTitle() {
return bookTitle;
}
String getBookAuthor() {
return bookAuthor;
}
String getBookDescription() {
return bookDescription;
}
String getBookId() {
return bookId;
}
int getCopies() {
return copies;
}
private void setBookUrl(String url) {
bookUrl = url;
}
String getBookUrl() {
return bookUrl;
}
}
}
This is the ProgramModel class from which I get item's datas:
public class ProgramModel {
private String title;
private String message;
private int image;
private String imageUrl;
public ProgramModel(String title, String message, int image) {
this.title = title;
this.message = message;
this.image = image;
}
public ProgramModel(String title, String message) {
this.title = title;
this.message = message;
}
public ProgramModel(String title, String message, String imageUrl) {
this.title = title;
this.message = message;
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getImageUrl() {
return this.imageUrl;
}
}
This is the main layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
tools:context="com.libraryhf.libraryharryfultz.activity.UserProfile">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/userImageId"
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:src="#drawable/prf_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_weight="3"
android:orientation="vertical"
android:padding="7dp">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/emailPrfId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/birthdayId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:paddingTop="7dp" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/userClassId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:paddingTop="7dp" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.v7.widget.RecyclerView
android:id="#+id/profileNewsFeed"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>
This is the single item layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/item_cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardBackgroundColor="#color/colorAccent"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="5dp"
card_view:contentPadding="7dp">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/bookTitleBorrowId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_margin="5dp"
android:text="#string/dummyText"
android:textColor="#color/white"
android:textSize="20sp" />
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="9dp"
android:layout_weight="7"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="1dp"
android:layout_weight="1"
app:srcCompat="#drawable/writer_icon" />
<TextView
android:id="#+id/bookAuthorBorrowId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_weight="6"
android:text="#string/dummyText"
android:textColor="#color/white"
android:textSize="13sp" />
</android.support.v7.widget.LinearLayoutCompat>
<ImageView
android:id="#+id/bookImageBorrowCardId"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
tools:ignore="ContentDescription" />
</android.support.v7.widget.LinearLayoutCompat>
</android.support.v7.widget.CardView>
</LinearLayout>
Unfortunately my items are not showing on the screen. I know that recyclerview is shown because I can notice the animations on top and on bottom but the items are not there. Where have I gone wrong here? Thank you.
Try adding adapter.notifyDataSetChanged(); after you add new element to the list. If you don't notify the adapter that the list changed, it won't update the recyclerview so that the data is always the empty list that is declared at the start.
you are accessing views from doInBackground, doInBackground is called on a different thread. you should access those views from onPostExecute(), an AsyncTask method that is called on the ui thread.
Please help me it would be great if anyone can get me thought this.
Here i'm trying to send details (EditText, String and Image Button Click) from kfcTab2.java to KFCdata.java
It shows an error
KFCdata(android.content.Context) in KFCdata cannot be applied
to(com.packagename)
kfcTab2.java
public class kfcTab2 extends Fragment implements View.OnClickListener {
ImageButton menu1;
EditText K_No;
String KNo;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.kfctab_2,container,false);
K_No = (EditText)v.findViewById(R.id.nos);
menu1 = (ImageButton)v.findViewById(R.id.kmenu1);
menu1.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.kmenu1:
String Name = "Rudresh";
String order = "Chicken Biriyani";
KNo = K_No.getText().toString();
KFCdata BackTask = new KFCdata(this);
BackTask.execute(Name,order,KNo);
break;
}
}
}
KFCdata.java
public class KFCdata extends AsyncTask<String,Void,String> {
Context ctx;
KFCdata(Context ctx){
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String ORDER_URL = "http://zesto596.96.lt/orders.php";
String Customer = params[0];
String Order = params[1];
String Quantity = params[2];
try {
URL url = new URL(ORDER_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
String data = URLEncoder.encode("CUSTOMER","UTF-8")+"="+URLEncoder.encode(Customer,"UTF-8")+"&"+
URLEncoder.encode("ITEM","UTF-8")+"="+URLEncoder.encode(Order,"UTF-8")+"&"+
URLEncoder.encode("QUANTITY","UTF-8")+"="+URLEncoder.encode(Quantity,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Item Added, please swipe to ORDERS...";
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
kfcTab2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent">
<TableRow>
<ImageView
android:layout_width="40sp"
android:layout_height="60sp"
android:src="#drawable/biryani"/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="Chicken Biriyani"
android:textSize="25sp"/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="description"
android:layout_marginLeft="-150sp"
android:layout_marginStart="-150sp"
android:layout_marginTop="30sp"/>
<EditText
android:id="#+id/nos"
android:layout_height="40sp"
android:layout_width="40sp"
android:background="#f3f3f3"
android:hint="Nos"
android:layout_marginLeft="100sp"/>
<ImageButton
android:id="#+id/kmenu1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="10sp"
android:src="#drawable/addtoplate"
android:onClick=""
android:background="#color/colorAccent"/>
</TableRow>
</TableLayout>
</RelativeLayout>
Replace in your code
this with current activity context
KFCdata BackTask = new KFCdata(this.kfcTab2.getActivity()); BackTask.execute(Name,order,KNo); break;
I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res``/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().