How can I do drag and drop recyclerView elements? - javascript

I have a project on android studio and I want to drag and drop images items in RecylerView to an Container on my Activity...
In my activity I have a fragment container and this displays fragments with an RecyclerView and this display animal parts in JSON connection, it's posible to make a Drag And Drop to move images to Cointainer to make a animal character and send data to my database, and how I do it???

You have to implement ItemTouchHelper and this is an example about how to do it:
1- Add your recyclerview
<android.support.v7.widget.RecyclerView
android:id="#+id/note_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2 - Add Model Class
public class Customer {
private Long id;
private String name;
private String emailAddress;
private int imageId;
private String imagePath;
}
3 - Add Dependencies
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.yqritc:recyclerview-flexibledivider:1.2.6'
compile 'com.google.code.gson:gson:2.3.1'
4 - Add Internet permission
<uses-permission android:name="android.permission.INTERNET" />
5- Create a new List of Customer in your Activity and add customers into it.
6- Create a new class named CustomerListAdapter
package com.okason.draganddrop;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.okason.draganddrop.listeners.OnCustomerListChangedListener;
import com.okason.draganddrop.listeners.OnStartDragListener;
import com.okason.draganddrop.utilities.ItemTouchHelperAdapter;
import com.okason.draganddrop.utilities.ItemTouchHelperViewHolder;
import com.squareup.picasso.Picasso;
import java.util.Collections;
import java.util.List;
/**
* Created by Valentine on 10/18/2015.
*/
public class CustomerListAdapter extends
RecyclerView.Adapter<CustomerListAdapter.ItemViewHolder>
implements ItemTouchHelperAdapter {
private List<Customer> mCustomers;
private Context mContext;
private OnStartDragListener mDragStartListener;
private OnCustomerListChangedListener mListChangedListener;
public CustomerListAdapter(List<Customer> customers, Context context,
OnStartDragListener dragLlistener,
OnCustomerListChangedListener listChangedListener){
mCustomers = customers;
mContext = context;
mDragStartListener = dragLlistener;
mListChangedListener = listChangedListener;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from
(parent.getContext()).inflate(R.layout.row_customer_list, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
final Customer selectedCustomer = mCustomers.get(position);
holder.customerName.setText(selectedCustomer.getName());
holder.customerEmail.setText(selectedCustomer.getEmailAddress());
Picasso.with(mContext)
.load(selectedCustomer.getImagePath())
.placeholder(R.drawable.profile_icon)
.into(holder.profileImage);
holder.handleView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mDragStartListener.onStartDrag(holder);
}
return false;
}
});
}
#Override
public int getItemCount() {
return mCustomers.size();
}
#Override
public void onItemMove(int fromPosition, int toPosition) {
Collections.swap(mCustomers, fromPosition, toPosition);
mListChangedListener.onNoteListChanged(mCustomers);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onItemDismiss(int position) {
}
public static class ItemViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
public final TextView customerName, customerEmail;
public final ImageView handleView, profileImage;
public ItemViewHolder(View itemView) {
super(itemView);
customerName = (TextView)itemView.findViewById(R.id.text_view_customer_name);
customerEmail = (TextView)itemView.findViewById(R.id.text_view_customer_email);
handleView = (ImageView)itemView.findViewById(R.id.handle);
profileImage = (ImageView)itemView.findViewById(R.id.image_view_customer_head_shot);
}
#Override
public void onItemSelected() {
itemView.setBahttp://valokafor.com/wp-admin/post.php?post=1804&action=edit#ckgroundColor(Color.LTGRAY);
}
#Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
}
7- Implement ItemTouchHelper
In your utilities package, add ItemTouchHelperAdapter.java and below is the content:
public interface ItemTouchHelperAdapter {
/**
* Called when an item has been dragged far enough to trigger a move. This is called every time
* an item is shifted, and not at the end of a "drop" event.
*
* #param fromPosition The start position of the moved item.
* #param toPosition Then end position of the moved item.
*/
void onItemMove(int fromPosition, int toPosition);
/**
* Called when an item has been dismissed by a swipe.
*
* #param position The position of the item dismissed.
*/
void onItemDismiss(int position);
}
And in your utilities package, add ItemTouchHelperViewHolder.java and below is the content:
public interface ItemTouchHelperViewHolder {
/**
* Implementations should update the item view to indicate it's active state.
*/
void onItemSelected();
/**
* state should be cleared.
*/
void onItemClear();
}
In your utilities package, add SimpleItemTouchHelperCallback.java and here is the content:
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return false;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView,
RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
#Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemSelected();
}
super.onSelectedChanged(viewHolder, actionState);
}
#Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemClear();
}
}
Add a package called listener and add an interface called OnStartDragListener.java and here is the content:
public interface OnCustomerListChangedListener {
void onNoteListChanged(List<Customer> customers);
}
Implement Custom Row
private RecyclerView mRecyclerView;
private CustomerListAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ItemTouchHelper mItemTouchHelper;
private List<Customer> mCustomers;
After the onCreate method, add this method. And then call this method from the onCreate() method probably after the call to set Toolbar. Ignore the error warning for a minute.
private void setupRecyclerView(){
mRecyclerView = (RecyclerView) `findViewById(R.id.note_recycler_view);`
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mCustomers = SampleData.addSampleCustomers();
//setup the adapter with empty list
mAdapter = new CustomerListAdapter(mCustomers, this, this, this);
ItemTouchHelper.Callback callback = new `SimpleItemTouchHelperCallback(mAdapter);`
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(mRecyclerView);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
.colorResId(R.color.colorPrimaryDark)
.size(2)
.build());
mRecyclerView.setAdapter(mAdapter);
}
Update the signature of your MainActivity to implement the two listeners that we added like below and use Android Studio quick fix to implement the methods.
public class MainActivity extends AppCompatActivity
implements OnCustomerListChangedListener,
OnStartDragListener{
Here is the implementation of one of the methods, and we will implement the other one in the next section.
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
At this point, your drag and drop list should be working and we now want to remember the position of the list items after they have been re-organized. Like I mentioned at the beginning of the post, this is accomplished by saving the ids of the list items to SharedPreference so go ahead and add the following class members to the top of the file.
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
public static final String LIST_OF_SORTED_DATA_ID = "json_list_sorted_data_id";
public final static String PREFERENCE_FILE = "preference_file";
And in the onCreate() instantiate the SharedPreference like so:
mSharedPreferences = this.getApplicationContext()
.getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
Then go ahead and implement the other method that listens for when the list changes and here is the implementation of that method:
#Override
public void onNoteListChanged(List<Customer> customers) {
//after drag and drop operation, the new list of Customers is passed in here
//create a List of Long to hold the Ids of the
//Customers in the List
List<Long> listOfSortedCustomerId = new ArrayList<Long>();
for (Customer customer: customers){
listOfSortedCustomerId.add(customer.getId());
}
//convert the List of Longs to a JSON string
Gson gson = new Gson();
String jsonListOfSortedCustomerIds = gson.toJson(listOfSortedCustomerId);
//save to SharedPreference
mEditor.putString(LIST_OF_SORTED_DATA_ID, jsonListOfSortedCustomerIds).commit();
mEditor.commit();
}
Then, add this method to your MainActivity.java:
private List<Customer> getSampleData(){
//Get the sample data
List<Customer> customerList = SampleData.addSampleCustomers();
//create an empty array to hold the list of sorted Customers
List<Customer> sortedCustomers = new ArrayList<Customer>();
//get the JSON array of the ordered of sorted customers
String jsonListOfSortedCustomerId = mSharedPreferences.getString(LIST_OF_SORTED_DATA_ID, "");
//check for null
if (!jsonListOfSortedCustomerId.isEmpty()){
//convert JSON array into a List<Long>
Gson gson = new Gson();
List<Long> listOfSortedCustomersId = gson.fromJson
(jsonListOfSortedCustomerId, new TypeToken<List<Long>>(){}.getType());
//build sorted list
if (listOfSortedCustomersId != null && listOfSortedCustomersId.size() > 0){
for (Long id: listOfSortedCustomersId){
for (Customer customer: customerList){
if (customer.getId().equals(id)){
sortedCustomers.add(customer);
customerList.remove(customer);
break;
}
}
}
}
//if there are still customers that were not in the sorted list
//maybe they were added after the last drag and drop
//add them to the sorted list
if (customerList.size() > 0){
sortedCustomers.addAll(customerList);
}
return sortedCustomers;
}else {
return customerList;
}
}
Now update the line in setupRecyclerView() that you get the data from:
mCustomers = SampleData.addSampleCustomers();
to:
mCustomers = getSampleData();
Here is the source of my answer you can find more information and description about every single step.

Related

Tab for 2 different fragment for auto update data, Intent?

Here is a tab for 2 fragment, at the 1st fragment click button_save it will perform save data and stay at current page, but when I tab to 2nd page which is 2nd fragment, the data wont update then i need to close my application and open back to the 2nd page fragment then only the data being update, how can i solve this problem that i no need close my application when tab to 2nd page and getting auto update the data in 2nd page ? use Intent ?
the code below is from 1st fragment
public class KeyInWeightF extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView=inflater.inflate(R.layout.daily_weight_fragement, container, false);
btnSave = (Button) contentView.findViewById(R.id.button_save);
dbconnection = new SQLControlerWeight(getActivity());
dbconnection.openDatabase();
btnSave.setOnClickListener(this);
return contentView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v){
switch (v.getId()){
case R.id.button_save:
if (btnTime.getText().toString().equals("")||btnDate.getText().toString().equals("")
||kgnum.getText().toString().equals("")||bf.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please insert all the detail!", Toast.LENGTH_LONG).show();
}
else{
String kgn = kgnum.getText().toString()+" kg";
String bodyfat = bf.getText().toString()+" %";
String date = btnDate.getText().toString();
String time = btnTime.getText().toString();
String comment = comm.getText().toString();
dbconnection.insertNote(kgn, bodyfat, date, time, comment);
Toast.makeText(getActivity(), "Suggest", Toast.LENGTH_LONG).show();
// Did i need add some code "Intent "here ??
}
break;
}
}
}
This is the 2nd fragment
public class HistoryF extends Fragment implements YourFragmentInterface{
View contentView;
ListView list;
SQLControlerWeight dbconnection;
TextView weight_num, date_num, time_num, bf_num, comment,weight_ID;
private SimpleCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.history_fragment, container, false);
dbconnection = new SQLControlerWeight(getActivity());
dbconnection.openDatabase();
list = (ListView) contentView.findViewById(R.id.listViewWeight);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
weight_ID = (TextView) view.findViewById(R.id.weight_id);
weight_num = (TextView) view.findViewById(R.id.weight_num);
bf_num = (TextView) view.findViewById(R.id.bf_num);
date_num = (TextView) view.findViewById(R.id.date_num);
time_num = (TextView) view.findViewById(R.id.time_num);
comment = (TextView) view.findViewById(R.id.comment_text);
String weightId = weight_ID.getText().toString();
String wn = weight_num.getText().toString();
String bfn = bf_num.getText().toString();
String dn = date_num.getText().toString();
String tn = time_num.getText().toString();
String cm = comment.getText().toString();
Intent modify_intent = new Intent(getActivity(), Update_detail_info.class);
modify_intent.putExtra("weightId", weightId);
modify_intent.putExtra("dateNum", dn);
modify_intent.putExtra("timeNum", tn);
modify_intent.putExtra("weightNum", wn);
modify_intent.putExtra("bodyFatNum", bfn);
modify_intent.putExtra("comment", cm);
startActivity(modify_intent);
}
});
return contentView;
}
#Override
public void fragmentBecameVisible() {
Cursor cursor = dbconnection.readNote();
String[] from = new String[]{
DBHelperNote.WEIGHT_ID,
DBHelperNote.WEIGHT_NUM,
DBHelperNote.BODY_FAT,
DBHelperNote.WEIGHT_DATE,
DBHelperNote.WEIGHT_TIME,
DBHelperNote.WEIGHT_COMMENTS
};
int[] to = new int[]{
R.id.weight_id,
R.id.weight_num,
R.id.bf_num,
R.id.date_num,
R.id.time_num,
R.id.comment_text
};
adapter = new SimpleCursorAdapter(
contentView.getContext(), R.layout.history, cursor, from, to,0);
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
this is my main activity :
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new KeyInWeightF(), "TRACK");
adapter.addFragment(new HistoryF(), "HISTORY");
adapter.addFragment(new AnalysisF(), "GRAPH");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Interface:
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
Sorry onResume() may not work correctly for tabs.In think you can implement the answer explained in this question.
create an interface as shown below:
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
Implement above interface in your 2nd fragmnet as shown below:
public class HistoryF extends Fragment implements YourFragmentInterface {
View contentView;
ListView list;
SQLControlerWeight dbconnection;
TextView weight_num, date_num, time_num, bf_num, comment,weight_ID;
private SimpleCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.history_fragment, container, false);
dbconnection = new SQLControlerWeight(getActivity());
dbconnection.openDatabase();
list = (ListView) contentView.findViewById(R.id.listViewWeight);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
weight_ID = (TextView) view.findViewById(R.id.weight_id);
weight_num = (TextView) view.findViewById(R.id.weight_num);
bf_num = (TextView) view.findViewById(R.id.bf_num);
date_num = (TextView) view.findViewById(R.id.date_num);
time_num = (TextView) view.findViewById(R.id.time_num);
comment = (TextView) view.findViewById(R.id.comment_text);
String weightId = weight_ID.getText().toString();
String wn = weight_num.getText().toString();
String bfn = bf_num.getText().toString();
String dn = date_num.getText().toString();
String tn = time_num.getText().toString();
String cm = comment.getText().toString();
Intent modify_intent = new Intent(getActivity(), Update_detail_info.class);
modify_intent.putExtra("weightId", weightId);
modify_intent.putExtra("dateNum", dn);
modify_intent.putExtra("timeNum", tn);
modify_intent.putExtra("weightNum", wn);
modify_intent.putExtra("bodyFatNum", bfn);
modify_intent.putExtra("comment", cm);
startActivity(modify_intent);
}
});
return contentView;
}
#Override
public void fragmentBecameVisible() {
Cursor cursor = dbconnection.readNote();
String[] from = new String[]{
DBHelperNote.WEIGHT_ID,
DBHelperNote.WEIGHT_NUM,
DBHelperNote.BODY_FAT,
DBHelperNote.WEIGHT_DATE,
DBHelperNote.WEIGHT_TIME,
DBHelperNote.WEIGHT_COMMENTS
};
int[] to = new int[]{
R.id.weight_id,
R.id.weight_num,
R.id.bf_num,
R.id.date_num,
R.id.time_num,
R.id.comment_text
};
adapter = new SimpleCursorAdapter(
contentView.getContext(), R.layout.history, cursor, from, to,0);
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
and in your MainActivity in onCreate() do the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
On implementing the interface you will have the function fragmentBecameVisible().
so whenever your fragment is active it will call the function fragmentBecameVisible(). which will update your tab. I think this solves your problem

Display append function in another new activity

I am doing an application which contains a listview of phone contact with a checkbox. I have found a coding that suits to my project. It works well but it does not operate as i want. I dont want 'respondText' appear in toast function, i just want it displayed in another new activity after the button clicked. I have tried the intent function, i put it under the toast funstion but the application does not perform. Maybe i just misplaced the function, what is the actual solution to handle this problem? Here is it :
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
final TextView textView = (TextView) findViewById(R.id.showAppend);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Contacts> countryList = dataAdapter.contactList;
for (int i = 0; i < countryList.size(); i++) {
Contacts country = countryList.get(i);
if (country.isSelected()) {
responseText.append("\n" + country.getName());
}
}
//Toast.makeText(getApplicationContext(), responseText,
//Toast.LENGTH_LONG).show();
Intent startNewAct = new Intent(ListViewCheckboxesActivity.thisthis, DisplayAppendActivity.class);
startActivity(startNewAct);
textView.setText(responseText);
}
});
}
Here is another new activity:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayAppendActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayappend);
TextView textView = (TextView) findViewById(R.id.showAppend);
String responseText = getIntent().getExtras().getString("responseText");
textView.setText(responseText);
}
}
You can send data through Intent. When starting actvity from intent you can use:
Intent startNewAct = new Intent(ListViewCheckboxesActivity.this, DisplayAppendActivity.class);
startNewAct.putExtra("responseText", responseText);
startActivity(startNewAct);
And you can get this responseText in another activity onCreate:
String responseText = getIntent().getExtras().getString("responseText");

Save in sharedPrefs from a class

hi all i've got this code to save some datas in sharedprefs but android studio tells me "getDefaultSharedPrefs in Preference Manager cannot be applied to com.foo.downloadDB.AttemptLogin" how can i do to solve this error?
i seems like i can't save to my sharedprefs from a "child" class
here is the code:
public class downloadDB extends Activity {
private EditText user, pass;
private android.widget.Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.myurl.com/users.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_db);
new AttemptLogin().execute();
}
public class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(downloadDB.this);
pDialog.setMessage("Download..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
editor1.putString("JSON_DB", json.toString());
editor1.commit();
System.out.println(editor1.commit());
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(downloadDB.this, file_url, Toast.LENGTH_LONG).show();
}
// Intent intent = new Intent(downloadDB.this, SampleActivity.class);
// startActivity(intent);
}
}
}
EDIT
I have this method in my SampleActivity class
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("name", "0") ;
String email = sharedPreferences.getString("email", "0") ;
String id = sharedPreferences.getString("id", "0") ;
String Database = sharedPreferences.getString("JSON_DB", "0") ;
Toast.makeText(this, Database, Toast.LENGTH_LONG).show();
//Toast.makeText(this, id, Toast.LENGTH_LONG).show();
//Toast.makeText(this, email, Toast.LENGTH_LONG).show();
}
and the Toast works fine, it prints me the JSON_DB correctly, but when i try to reach it from the respective Fragment it doesn't work.. here is my fragment code :
public class SampleFragment extends Fragment {
public static String KEY_ID = "id";
public static String KEY_EMAIL = "email";
public static String KEY_NAME = "name";
public static String JSON_DB = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LoadPreferences();
Log.i("string", KEY_EMAIL);
Log.i("string", KEY_ID);
Log.i("string", KEY_NAME);
Log.i("string", JSON_DB);
and KEY_EMAIL, KEY_ID and other objects logs correctly..
This is the problem:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
this is the instance of the AsyncTask instead Activity
use downloadDB.this instead only this; but please call your class using Uppercase (DownloadDB)

Unable To Insert An Array Selection into a Database

First off, I would just like to mention that my problem isn't as easy as the title suggests. Here is my problem. Basically I am trying to set the value of a string to a randomly selected item in a string array. Shown here:
String[] array = getResources().getStringArray(R.array.states);
selected_state = array[new Random().nextInt(array.length)];
When a button is pushed, this string is insert into my database. Like this:
long id = database_helper.insertData(selected_state);
It seem like it should work, but unfortunately for me it does not. Apparently selected_state is null when I try to insert it. But another string in my app that is pulled from an editText and inserted the exact same way is totally fine. Here are the relevant parts of my code:
public class my_class extends Fragment implements View.OnClickListener {
View rootView;
Button bing;
EditText text;
public String selected_state;
public String TEXT;
DatabaseAdapter database_helper;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.my_fragment, container, false);
bing = (Button) rootView.findViewById(R.id.my_btn);
text = (EditText) rootView.findViewById(R.id.my_text_edit);
String[] array = getResources().getStringArray(R.array.states);
selected_state = array[new Random().nextInt(array.length)];
bing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send();
}
private void send() {
TEXT = text.getText().toString();
//VALUE HOLDS UP TO HERE
long id = database_helper.insertData(TEXT, selected_state);//NULL!!!!!!
if(id<0){
Toast.makeText(getActivity(), "SHES STUCK", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "SHES IN", Toast.LENGTH_LONG).show();
text.setText("");
}
}
});
return rootView;
}
#Override
public void onClick(View v) {
}
}
Thanks everyone!
EDIT The string (or what I believe to be a string) value has been carried down to the same place TEXT is. Marked above

How to Pass JSF Bean data to JavaScript Function?

I am passing data with the below code:
<p:poll interval="3" listener="#{chartController.loadChartData}" oncomplete="renderChart('container','area','Sample Chart', '#{chartController.chartData}', '#{chartController.categories}');"
id="chartvalue_btn" update="textID" />
But when I checked null value is passed in JavaScript function while I checked bean variable initialized with values. Am I doing something wrong here?
ANd my bean is
package com.bchetty.charts.controller;
import com.bchetty.charts.model.Series;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
/**
* Chart Controller
*/
#ManagedBean(name="chartController")
#SessionScoped
public class ChartController {
private String chartData;
private String categories;
private List<String> categoryList = new ArrayList<String>();
private List<Long> heapSizeList = new ArrayList<Long>();
private List<Long> usedHeapSizeList = new ArrayList<Long>();
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss");//dd/MM/yyyy
private static final long MB = 1024*1024;
int index = 0;
private Long[] longs;
/**
* Load Chart Data
*/
public void loadChartData() {
if(heapSizeList.size() > 10) {
heapSizeList.remove(0);
usedHeapSizeList.remove(0);
categoryList.remove(0);
}
List<Series> series = new ArrayList<Series>();
malloc();
long heapSize = Runtime.getRuntime().maxMemory();
heapSizeList.add(heapSize/MB);
usedHeapSizeList.add((heapSize - Runtime.getRuntime().freeMemory())/MB);
series.add(new Series("Heap Size", heapSizeList));
series.add(new Series("Used Heap", usedHeapSizeList));
setChartData(new Gson().toJson(series));
categoryList.add(sdfDate.format(new Date()));
System.out.println(categoryList);
setCategories(new Gson().toJson(categoryList));
}
/**
* #return the chartData
*/
public String getChartData() {
return chartData;
}
/**
* #param chartData the chartData to set
*/
public void setChartData(String chartData) {
this.chartData = chartData;
}
/**
* #return the categories
*/
public String getCategories() {
return categories;
}
/**
* #param categories the categories to set
*/
public void setCategories(String categories) {
this.categories = categories;
}
private void malloc() {
if(index%2 == 0) {
longs = new Long[100000];
for(int i=0;i<1000;i++) {
longs[i] = Long.valueOf(i);
}
} else {
longs = null;
}
index++;
}
}
The problem is that the arguments of the oncomplete-function are only updated when the view is entered. The arguments are not automatically updated when the value of the properties on the bean have changed. So as chartController.chartData is initially not instanciated it is null when the page is rendered and remains null until you manually refresh the whole page.
To fix this issue I would recommend you to use the Primefaces RequestContext and add the chartData everytime loadChartData is called as a callback param.
I.e. add the following to the and of loadChartData:
public void loadChartData() {
...
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("chartData", chartData);
context.addCallbackParam("categories", categories);
}
And in the UI define the p:poll as follows:
<p:poll interval="3" listener="#{chartController.loadChartData}"
oncomplete="renderChart('container','area','Sample Chart', args.chartData, args.categories);"
id="chartvalue_btn" update="textID" />
If this is no option for you, because you are using loadChartData anywhere else, wrap the call of loadChartData with the addCallbackParam stuff in another method and specify this method as listener of the p:poll.

Categories

Resources