I have this custom adapter and I don´t know why throws exception if views are in layout inflated.
I then use the adapter un a new class to show listview. What is null?
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.save.coinch.R;
import com.save.coinch.SQLiteDB;
import com.save.coinch.responses.Saving;
import com.save.coinch.responses.Transaction;
import com.save.coinch.responses.User;
import com.save.coinch.utils.CacheUtils;
import com.save.coinch.utils.CommonUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class TransactionsAdapter extends BaseAdapter {
private List<Transaction> items;
LayoutInflater li;
public TransactionsAdapter(Context context, List<Transaction> items) {
super();
this.items = items;
this.li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
//LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.trans_item, parent, false);
null pointer exception here
holder.txtViewAmount = (TextView) convertView.findViewById(R.id.trans_amount);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.trans_date);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.trans_title);
convertView.setTag(holder);
}else
holder = (ViewHolder) convertView.getTag();
Transaction app = items.get(position);
if (app != null) {
holder.txtViewDate.setText(app.getDate());
holder.txtViewAmount.setText(Float.toString(app.getAmount()));
holder.txtViewTitle.setText(app.getTitle());
}
return v;
}
public static class ViewHolder {
TextView txtViewAmount;
TextView txtViewDate;
TextView txtViewTitle;
}
}
Trans_Item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip">
<!-- ListRow Left side Thumbnail image -->
<TextView
android:id="#+id/trans_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/tit_prin"
android:textAlignment="center"
android:textColor="#ff902020"
android:textSize="10sp"
android:textStyle="bold"
android:typeface="sans"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/trans_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tit_prin"
android:textSize="15sp"
android:textStyle="bold"
android:layout_alignBottom="#+id/trans_amount"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/trans_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tit_prin"
android:textSize="25sp"
android:textStyle="bold"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<!--</LinearLayout>-->
</RelativeLayout>
ShowList.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.save.coinch.adapters.TransactionsAdapter;
import com.save.coinch.interfaces.RequestCallBack;
import com.save.coinch.network.FetchDataListener;
import com.save.coinch.network.FetchDataTask;
import com.save.coinch.network.Request;
import com.save.coinch.responses.Savings;
import com.save.coinch.responses.Transaction;
import com.save.coinch.responses.Transactions;
import com.save.coinch.responses.User;
import com.save.coinch.utils.CacheUtils;
import com.save.coinch.utils.CommonUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* Created by Joel_2 on 07/05/2015.
*/
public class TransRecord extends ListActivity implements FetchDataListener {
ListView data;
TransactionsAdapter adapter;
JSONArray json;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trans_data);
initView();
//data = (ListView) findViewById(R.id.trans_all);
// adapter = new TransactionsAdapter(this);
//data.setAdapter(adapter);
}
private void initView() {
// show progress dialog
String url = CommonUtils.SERVICES.FETCH_TRANSACTIONS;
FetchDataTask task = new FetchDataTask(this);
//ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
User user = CacheUtils.getUser(this);
task.setParameters(new BasicNameValuePair("user_id", String.valueOf(user.user_id)));
task.execute(url);
}
#Override
public void onFetchComplete(List<Transaction> data) {
// create new adapter
TransactionsAdapter adapter = new TransactionsAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Please help :)
Exception is in this area
if (v == null) {
holder = new ViewHolder();
//LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.trans_item, parent, false);
holder.txtViewAmount = (TextView) convertView.findViewById(R.id.trans_amount);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.trans_date);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.trans_title);
convertView.setTag(holder);
}
you must use v instaed convertView
Related
I am making an android ecommerce app and I downloaded an app template but in that template there is no firebase in the fragment and I want when the user clicks checkout button the products he selected should go to the firebase database but all videos I see they use activities .So please help me.
CartFragment.java
package com.example.shoppingcart.views;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.shoppingcart.R;
import com.example.shoppingcart.adapters.CartListAdapter;
import com.example.shoppingcart.cartholder;
import com.example.shoppingcart.databinding.FragmentCartBinding;
import com.example.shoppingcart.dataholder;
import com.example.shoppingcart.models.CartItem;
import com.example.shoppingcart.productholder;
import com.example.shoppingcart.viewmodels.ShopViewModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class CartFragment extends Fragment implements CartListAdapter.CartInterface {
private static final String TAG = "CartFragment";
private ImageView productImage;
private TextView productname;
private TextView productprice;
private TextView productcategory;
private Spinner productquantity;
UUID uuid = UUID.randomUUID();
String randomUUID = uuid.toString().trim();
ShopViewModel shopViewModel;
FragmentCartBinding fragmentCartBinding;
NavController navController;
Button button;
private void finishActivity() {
if (getActivity() != null) {
getActivity().finish();
}
}
public CartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCartBinding = FragmentCartBinding.inflate(inflater, container, false);
return fragmentCartBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
final CartListAdapter cartListAdapter = new CartListAdapter(this);
fragmentCartBinding.cartRecyclerView.setAdapter(cartListAdapter);
fragmentCartBinding.cartRecyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
shopViewModel = new ViewModelProvider(requireActivity()).get(ShopViewModel.class);
shopViewModel.getCart().observe(getViewLifecycleOwner(), new Observer<List<CartItem>>() {
#Override
public void onChanged(List<CartItem> cartItems) {
cartListAdapter.submitList(cartItems);
fragmentCartBinding.placeOrderButton.setEnabled(cartItems.size() > 0);
}
});
shopViewModel.getTotalPrice().observe(getViewLifecycleOwner(), new Observer<Double>() {
#Override
public void onChanged(Double aDouble) {
fragmentCartBinding.orderTotalTextView.setText("Total: PKR " + aDouble.toString());
}
});
button = (Button) getView().findViewById(R.id.placeOrderButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CartFragment.this.getActivity(), CheckoutActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finishActivity();
}
});
}
#Override
public void deleteItem(CartItem cartItem) {
shopViewModel.removeItemFromCart(cartItem);
}
#Override
public void changeQuantity(CartItem cartItem, int quantity) {
shopViewModel.changeQuantity(cartItem, quantity);
}
}
fragment_cart.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<LinearLayout
android:orientation="vertical"
tools:context=".views.CartFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cartRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="#layout/cart_row"
tools:itemCount="2"
/>
<Space
android:layout_width="match_parent"
android:layout_height="16dp" />
<TextView
android:id="#+id/orderTotalTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Total: PKR 26"
android:textAppearance="#style/TextAppearance.MaterialComponents.Headline6" />
<Button
android:id="#+id/placeOrderButton"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Proceed To Checkout"
android:textAppearance="#style/TextAppearance.MaterialComponents.Caption" />
</LinearLayout>
</ScrollView>
What kind of firebase database you have to use because both of the methods are similar...
activity and fragment method is same not any kind of change to the method ...
i will show you firestore method because i don't know which one you have to use
in fragment first initilize
FirebaseFirestore firebaseFirestore;
oncreateview initialize
firebaseFirestore = FirebaseFirestore.getInstance();
after you can perform all your crud operation and all thing but first two line is require
simple use bro...
I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment. I am using recycler view inside the search fragment to display the data below the search bar and the button.
Here is the code for the fragment_search.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".Fragments.SearchFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="-230dp"
android:src="#drawable/home_oval" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FOODIES"
android:textSize="40dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:queryHint="Find your today's recipe"
android:iconifiedByDefault="false"
android:background="#drawable/searchoval"
android:id="#+id/searchbar"
/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="search"
android:background="#drawable/rounded_btn"
android:layout_below="#+id/searchbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button1"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_man_searching_location_using_gps_2127154_0"
android:layout_below="#+id/button1"
android:id="#+id/searching_logo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searching_text"
android:text="Search for yummy delicacies today"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:fontFamily="#font/quicksand"
android:layout_below="#+id/searching_logo"
android:textSize="25dp"
android:textColor="#color/black"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:id="#+id/recycler_view"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</FrameLayout>
Here is my SearchFragment.java file.
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
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.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "http://localhost:5000/" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonArrayRequest);
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I am fething the api and setting the arraylists and adapter inside the onClick listener
but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.
Here is the code for the adapter.
package com.example.recipeappandroid.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
private Context mContext;
private ArrayList<Recipe> mRecipe;
public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
mContext = context;
mRecipe = recipe;
}
public void setData(ArrayList<Recipe> mRecipe) {
this.mRecipe = mRecipe;
}
#NonNull
#Override
public recipeViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
return new recipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull recipeViewHolder viewHolder, int i) {
Recipe recipe = mRecipe.get(i);
Picasso.get().load(recipe.getImg()).into(viewHolder.image);
viewHolder.recipe_title.setText(recipe.getTitle());
viewHolder.recipe_data.setText(recipe.getData());
}
#Override
public int getItemCount() {
return mRecipe.size();
}
}
Here is my solution
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);
//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
I had tried do Spinner in some Fragment. I was doing that with tutorial on Youtube. So, I just rewrite all from that tutorial.
Firstly, in string : ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
my Android Studio didn`t saw android. It is just underlined in red, so I write :
ArrayAdapter adapter = new ArrayAdapter(this.getActivity(), android.R.layout.simple_spinner_item);
there were no errors at startup, but when I try to click on the spinner, the application crashes
This is my Fragment:
package com.example.itss;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class SettingsFragment extends Fragment {
private Spinner timeOfSleep;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.settings_fragment,container, false);
timeOfSleep = v.findViewById(R.id.timeOfsleep);
List<TimeOfSleep> timeOfSleepList = new ArrayList<>();
TimeOfSleep time5 = new TimeOfSleep(5);
timeOfSleepList.add(time5);
TimeOfSleep time10 = new TimeOfSleep(10);
timeOfSleepList.add(time10);
TimeOfSleep time15 = new TimeOfSleep(15);
timeOfSleepList.add(time15);
ArrayAdapter<TimeOfSleep> adapter = new ArrayAdapter<TimeOfSleep>(this.getActivity(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
timeOfSleep.setAdapter(adapter);
timeOfSleep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TimeOfSleep tOS = (TimeOfSleep) parent.getSelectedItem();
displaytimeOfSleep(tOS);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
public void getSelectedtimeOfSleep(View v){
TimeOfSleep tOS = (TimeOfSleep) timeOfSleep.getSelectedItem();
displaytimeOfSleep(tOS);
}
private void displaytimeOfSleep(TimeOfSleep a){
int time = a.getTimeOfSleep();
}
}
Also java class
package com.example.itss;
public class TimeOfSleep {
private int timeOfSleep;
public TimeOfSleep(int timeOfSleep) {
this.timeOfSleep = timeOfSleep;
}
public int getTimeOfSleep() {
return timeOfSleep;
}
public void setTimeOfSleep(int timeOfSleep) {
this.timeOfSleep = timeOfSleep;
}
#Override
public String toString() {
String a = timeOfSleep + " мин";
return a;
}
}
And xml:
<?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="vertical"
android:background="#000000"
android:padding="25dp"
android:paddingBottom="100dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Время засыпания:"
android:background="#color/colorPrimary"
android:textColor="#FFFFFF"
android:onClick="getSelectedtimeOfSleep"/>
<Spinner
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_arrow_drop_down_black_24dp"
android:id="#+id/timeOfsleep">
</Spinner>
</LinearLayout>
</LinearLayout>
In Logs I have just: 16:28 Can't bind to local 8600 for debugger
If you are getting an error saying can't bind, then you need to restart your adb server by killing it first and starting it again.
adb kill-server
adb start-server
You can do this from the terminal
When I scroll past an item and come back to it, it changes it's position until I click on it, then it will correctly align itself. How can I solve this. Sorry I am still at the start of the project so my code is a bit messy.
This is my code:
package com.example.r_corp.androidslauncher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
PackageManager packageManager;
Intent mainIntent = null;
static ArrayList<app> appList;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_all_apps_layout);
gridView = (GridView)findViewById(R.id.GridView);
gridView.setNumColumns(4);
packageManager = getPackageManager();
mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appList = getApps();
show();
}
public ArrayList<app> getApps(){
List<ResolveInfo>apps = packageManager.queryIntentActivities(mainIntent, 0);
ArrayList<app> Apps = new ArrayList();
for(ResolveInfo ri : apps){
app App = new app();
App.icon = ri.loadIcon(packageManager);
App.Name = ri.loadLabel(packageManager).toString();
Apps.add(App);
}
return Apps;
}
public void show(){
ArrayAdapter<app> adapter = new ArrayAdapter<app>(this, R.layout.item,
appList) {
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item,null);
}
ImageView appIcon = (ImageView) convertView
.findViewById(R.id.imageView);
appList.get(position).icon.setBounds(10,10,10,10);
appIcon.setImageDrawable(appList.get(position).icon);
appIcon.setLayoutParams(new RelativeLayout.LayoutParams(85, 85));
appIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
appIcon.setPadding(8, 8, 8, 8);
TextView appName = (TextView) convertView
.findViewById(R.id.textView);
appName.setText(appList.get(position).Name);
return convertView;
}
};
gridView.setFocusable(true);
gridView.setAdapter(adapter);
}
}
class app{
Drawable icon;
String Name;
}
show_all_apps_layout:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:stretchMode="columnWidth"
android:focusableInTouchMode="true"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:id="#+id/GridView"/>
item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
Thanks in advance for your helpfulness.
I have a listView where a user can enter input to change the textView on each listView row. When you scroll the row off the screen the edited text goes away and the default text reappears. I know this is fixed with the viewHolder but I can't get it to work in my custom adapter class.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> Chores = new ArrayList<>();
//Chores.add("");
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Chores.add("");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.emilythacker.chorelist.R.id.textView_ID;
class CustomAdapter extends ArrayAdapter{
ArrayList<String> choreText;
public CustomAdapter(Context context, ArrayList choreText) {
super(context, R.layout.custon_listview_row, choreText);
this.choreText = choreText;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//final TextView textView = (TextView) customView.findViewById(textView_ID);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.custon_listview_row, null);
holder = new ViewHolder();
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imageButton_ID);
holder.textView = (TextView) convertView.findViewById(textView_ID);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(choreText.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//what happens when textView is clicked
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
final EditText input = new EditText(getContext());
input.setHint("hint");
alertDialog.setView(input);
alertDialog.setTitle("Set Chore");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
holder.textView.setText(input.getText().toString());
dialog.dismiss();
}
});
alertDialog.show();
}
});
holder.imageButton.setImageResource(R.drawable.clock);
return convertView;
}
static class ViewHolder {
ImageButton imageButton;
TextView textView;
}
}
activity_main.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:id="#+id/activity_main"
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.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
custon_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<TextView
android:text="Click here to add chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/textView_ID"
android:textSize="25dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/imageButton_ID"
android:layout_marginEnd="11dp"
/>
</RelativeLayout>
When text is entered into the edit text, you need to save it to a variable associated with that position, and in getView you need to set the text of the editText to that position's value. Otherwise you'll just have whatever random value was in there last.
Basically, any value that can change in a row's UI must be saved and written to it in getView.