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...
Related
I have an android application and i want to display database data in one of the activity in a listview. I already managed to display it in a listview on a fragment, but now i want to apply the same process to an activity.
I already tried to take the code i used to display data on my fragment, and use it for my activity, but didn't work even after making some change, and i'm still getting an error on #Override.
Here is my activity code :
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[] .
{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}```
Here is my layout holding the listview :
```<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/CDCANGList"/>
</RelativeLayout>```
And here is my layout for the arrangement of each row of the listview :
```<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<TextView
android:id="#+id/ContenuANG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ContenuANGDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="24dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView7"
app:layout_constraintTop_toBottomOf="#+id/ContenuANG" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_histgeo"
android:text="Travail effectuer :"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginLeft="72dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="152dp"
android:layout_marginRight="152dp"
android:text="Date : "
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>```
I'm expecting each row of the table to display in the listview of my activity. I'm getting the following error message caused by the "#Override" : "error: method does not override or implement a method from a supertype".
'onCreateView() method is only for fragment it cannot be override in activity.'
put you all the code in onCreate() method of your activity. it will be working pretty fine Thanks
if you feel any other problem please discuss
Thanks you a lot for your answer! I did the modification, but now i'm having some troubles on my layout inflater and my retur rootView. Any ideas how i could correct this? See my code below.
package com.example.schoolapp.Admin;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[]{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}
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 am just getting into android apps and now trying to work with an interface that allows the user to enter date into a text box. The date dialog should only display when a text box is focused.After a date is selected from the dialog, it will be displayed in the text box. The problem now is the date dialog is displayed even the text box is not focused. Can someone help me to figuring out my problem? Thank.
TimeSheet.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<EditText
android:layout_width="190dp"
android:layout_height="wrap_content"
android:id="#+id/txtdate"
android:layout_x="131dp"
android:layout_y="192dp"
android:hint="Touch here to select a date"/>
</AbsoluteLayout>
TimeSheet.java
package com.example.project.project;
import android.app.DatePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.view.View;
import android.os.Bundle;
import android.widget.Button;
import java.util.List;
import java.util.ArrayList;
import android.content.Context;
import android.content.ContentValues;
import android.widget.Toast;
import com.example.project.project.API.TimeSheetAPI;
import com.example.project.project.database.MyDatabaseHelper;
public class TimeSheet extends AppCompatActivity {
private Spinner spinner,spinner2;
private Button btnSaved;
private MyDatabaseHelper dbHelper;
private TimeSheetAPI ts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timesheet);
ts=new TimeSheetAPI(this);
}
public void onStart()
{
super.onStart();
EditText txtDate=(EditText)findViewById(R.id.txtdate);
txtDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if(hasFocus)
{
DateDialog dialog=new DateDialog(v);
FragmentTransaction ft=getFragmentManager().beginTransaction();
dialog.show(ft,"DatePicker");
}
}
});
}
DateDialog.java
package com.example.project.project;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
/**
* Created by tongws on 9/14/2015.
*/
#SuppressLint("ValidFragment")
public class DateDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener {
EditText txtdate;
public DateDialog(View view)
{
txtdate=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c=Calendar.getInstance();
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),this,year,month,day);
}
public void onDateSet(DatePicker view,int year, int month, int day)
{
String date=day+"-"+(month+1)+"-"+year;
txtdate.setText(date);
}
}
Your EditText has been focused once the activity started. To clear default focus on EditText, add focus to the parent layout. This can be done by adding this line of code into your parent view.
android:focusableInTouchMode="true"
For example,
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1"
android:focusableInTouchMode="true">
<EditText
android:layout_width="190dp"
android:layout_height="wrap_content"
android:id="#+id/txtdate"
android:layout_x="131dp"
android:layout_y="192dp"
android:hint="Touch here to select a date"/>
</AbsoluteLayout>
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