Unable to retrieve value from other class method - android

i have a foll. method in class A
public String getContactNameFromNumber(String number) {
// define the columns I want the query to return
String[] projection = new String[]{
Phones.DISPLAY_NAME,
Phones.NUMBER};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(fname));
// query time
Cursor c = getContentResolver().query(contactUri, projection, null,
null, null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(Phones.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
i want to retrive value from the variable fname and insert the value in listview of other class B

You can get the value from this method in any public static variable
And then in class B you can write ClassA.name_of_static_variable;

An example with static reference as a bridge communication between classes
//ClassA
public class ClassA {
public static String fName = "";
public void getContactNameFromNumber(String number) {
//calucate fName value
}
}
//ClassB
public class ClassB {
public static String fName = "";
private void fromSomeMethod() {
String fName = ClassA.fName;
}
}

Suppose you have two classes ClassA and ClassB.
Any method in ClassA that return value so you can get that value in public static variable.
public static String _varName = null; // get you return value in this variable.
And in ClassB you can just write the name of ClassA._varName;
then you can get the value of ClassA in ClassB.

Related

How to get assign values to an arraylist item inside a cursor iterator

I am trying to assign one variable to an ArrayList item inside a cursor but it always returns me last value. Here is the code below.
Getting value from DB
public ArrayList<Bean> getPendingData(String s) {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {name};
String[] selectionArgs = {s};
Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null);
cursor.moveToFirst();
ArrayList<Bean> pending = new ArrayList<>();
String index0 = null;
Bean bean;
bean = new Bean();
while(!cursor.isAfterLast()) {
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
cursor.close();
return pending;
}
Bean.java
public class Bean {
public static int id; // ans
public static String score;
public static String logo;
public static String image;
public static String getQuestion() {
return question;
}
public static void setQuestion(String question) {
Bean.question = question;
}
public static String question;
public static String description;
public static String option_three;
public static String OptionFour;
}
You should initialize your bean inside the while block:
while(!cursor.isAfterLast()) {
Bean bean = new Bean();
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
The reason is that Java uses objects by reference, so you're always adding the same object to the array "pending", but in following iterations you're changing the value of this object, so finally you have the value of the last iteration.
cursor.isAfterLast() returns true when cursor is at last row position. Adding a ! (not) means perform till it is not at the end of cursor.
so while(!cursor.isAfterLast()){} means while loop will traverse till last record of cursor.
Use this method to fetch all rows returning from cursor.
if (cursor != null) {
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
homeClassesArrayList = new ArrayList<>();
do {
// fetching data
} while (cursor.moveToNext());
}
}
}

Android Studio activity passing data

I have 3 activities - login activity, main page activity, profile activity. The login activity will call main page activity and main page activity will call profile activity. How can I pass the data from login activity to profile activity? Is it must pass the data from login activity to main page activity first then pass to profile activity from main page activity? Or is there any other way to pass the data? Thanks!
You can do that... or you could store the data in a persistent storage and read back whenever required.
Learn about SharedPreferences here - Saving Key-Value Sets | SharedPreferences
Saving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Retrieving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Learn about SQLite Database here - Saving Data in SQL Databases | SQLite Database
Saving data looks like:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
Retrieving data looks like:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
List itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID));
itemIds.add(itemId);
}
cursor.close();
There are two methods to pass values between Activities in Android:
1. Using intent:
Example:
In the Login Activity, put the following code inside the OnClickListiner:
Intent intent = new Intent(getApplicationContext(), mainActivity.class);
intent.putExtra("username", usernameVariable);
intent.putExtra("password", passwordVariable);
startActivity(intent);
Then, on the mainActivity, to receive the values use the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String u = intent.getStringExtra("username");
String p = intent.getStringExtra("password");
// note: the arguments should match the same as its in the loginActivity
}
2. Using Static Variables:
Example:
On the LoginActivity, create two static attributes. Like the following:
Public Class LoginActivity{
public static String username;
public static String password;
protected void onCreate(Bundle savedInstanceState) {
...
}
}
Then, in the mainActivity class use the following code to get these values:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
String u=LoginActivity.username;
String p=LoginActivity.password;
}
Hope it solved your problem...
There is one more way that you can use create a singleton class and store the value and use it.
public final class ProfileDataModel {
private static ProfileDataModel instance;
private String userName;
private String address;
private ProfileDataModel() {
}
/**
* Get Instance for Profile
* #return
*/
public static ProfileDataModel getInstance() {
if (instance == null){
instance = new ProfileDataModel();
}
return instance;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
// Use cases
//Set the data
ProfileDataModel.getInstance().setAddress("Data from login response");
ProfileDataModel.getInstance().setUserName("As per request/response");
//Get the data
String address = ProfileDataModel.getInstance().getAddress();
String userName = ProfileDataModel.getInstance().getUserName();

i dont know how to declare Cursor and get method at same time and use it Cursor c? what i need too is to return all the names

I have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);

Paramaters with the same value - android

I have a listview that shows this paramaters. But 2 of the parameters returns the same value? How can I differentiate this two? Its email and voucher.
VoucherObj obj = new VoucherObj();
obj.customerID=item[0];
obj.type=item[1];
obj.name=item[2];
obj.searchStr=item[3]; <---- SAME PARAMETER
obj.searchStr=item[4]; <---- SAME PARAMETER
obj.branch=item[5];
obj.issued=item[6];
obj.expiration=item[7];
obj.status=item[8];
obj.vouchername=item[9];
obj.employeeid=item[10];
items.add(obj);
Voucher.class
public class VoucherObj {
public String customerID="";
public String type="";
public String name="";
public String email="";
public String voucher="";
public String branch="";
public String issued = "";
public String expiration="";
public String status = "";
public String vouchername = "";
public String employeeid = "";
public String searchStr;
}
If you'll have a static amount of items, you can declare the searchStr field of your VoucherObj as a static array with a fixed size. Assuming you're storing Strings, this would be:
String[] searchStr = new String[10];
If the number of items of that field is unknown, just use a more advanced data structure, for instance:
ArrayList<String> searchStr = new ArrayList<String>();
Afterwards you can use this method to add a value:
obj.searchStr.add("value1");
obj.searchStr.add("value2");
...
public class VoucherObj(){
int customerId;
..............
..............
ArrayList<String> searchStr;
..............
/*other parameters here*/
}
and in your main class use
obj.searchStr.add(item[3]);
obj.searchStr.add(item[4]);

Storing data into String array and pass it to AsyncTask

I am getting all of my contacts details from contactconstract table, and Want to store all my contact data to String array then I would like to pass it to AsyncTask for doing some background task,Currently I am passing single contacts detail to AsyncTask,that would made my code crash because one by one asynctask is being called for each contact detail, I would like to store all my contact detail into array an then I pass this array to AsyncTASK so only one time AsyncTask would call so Please help me in this regard,
Given below is my part of the code:
ContentResolver cr = getContentResolver();
SavingContacts savingcontacts=new SavingContacts();
Cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC");
Log.d("database1" ,"17");
if (Cursor.getCount() > 0) {
while (Cursor.moveToNext()) {
phone = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phone)) {
Log.d("Your Location4", "ok4:");
name = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
id = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
// photouri=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
email=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("contactId="+ id+ ", name=" + name + ", phoneNumber=" + phone+"Email="+email);
}
savingcontacts.savingcontact(id, name, phone, email);
}
}
Cursor.close();
I am doing this work In oncreate function of activity
//////////////////////////////////////////////////////////////////
Activity Class
public class ContactsListActivity extends FragmentActivity implements
ContactsListFragment.OnContactsInteractionListener {
// Defines a tag for identifying log entries
private static final String TAG = "ContactsListActivity";
private Cursor Cursor;
private ContactDetailFragment mContactDetailFragment;
public DBHandler db;
// If true, this is a larger screen device which fits two panes
private boolean isTwoPaneLayout;
String id,name,phone, email;
// True if this activity instance is a search result view (used on pre-HC devices that load
// search results in a separate instance of the activity rather than loading results in-line
// as the query is typed.
private boolean isSearchResultView = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
Log.d("Hope","Hope 8");
// Set main content view. On smaller screen devices this is a single pane view with one
// fragment. One larger screen devices this is a two pane view with two fragments.
setContentView(R.layout.activity_main);
// Getallcontacts();
// Check if two pane bool is set based on resource directories
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
// Check if this activity instance has been triggered as a result of a search query. This
// will only happen on pre-HC OS versions as from HC onward search is carried out using
// an ActionBar SearchView which carries out the search in-line without loading a new
// Activity.
if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
// Fetch query from intent and notify the fragment that it should display search
// results instead of all contacts.
String searchQuery = getIntent().getStringExtra(SearchManager.QUERY);
ContactsListFragment mContactsListFragment = (ContactsListFragment)
getSupportFragmentManager().findFragmentById(R.id.contact_list);
Log.d("Hope","Hope 47");
// This flag notes that the Activity is doing a search, and so the result will be
// search results rather than all contacts. This prevents the Activity and Fragment
// from trying to a search on search results.
isSearchResultView = true;
mContactsListFragment.setSearchQuery(searchQuery);
// Set special title for search results
String title = getString(R.string.contacts_list_search_results_title, searchQuery);
setTitle(title);
}
if (isTwoPaneLayout) {
// If two pane layout, locate the contact detail fragment
mContactDetailFragment = (ContactDetailFragment)
getSupportFragmentManager().findFragmentById(R.id.contact_detail);
}
ContentResolver cr = getContentResolver();
// SavingContacts savingcontacts=new SavingContacts();
ArrayList<SavingContacts> contacts = new ArrayList<SavingContacts>();
Cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC");
Log.d("database1" ,"17");
if (Cursor.getCount() > 0) {
while (Cursor.moveToNext()) {
SavingContacts savingcontacts=new SavingContacts();
phone = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phone)) {
Log.d("Your Location4", "ok4:");
name = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
id = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
// photouri=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
email=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("contactId="+ id+ ", name=" + name + ", phoneNumber=" + phone+"Email="+email);
savingcontacts.savingcontact(id, name, phone, email);
contacts.add(savingcontacts);
}
}
}
Cursor.close();
new LoadSavingInDatabase.execute(contacts);
}
public static class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{
private static final String TAG_SUCCESS = "success";
private static final String URL = "http://amiranzur.com/android_connect/create_product.php";
JSONObject jsonObject= null;
#Override
protected String doInBackground(ArrayList<SavingContacts>... params) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("email" , email ));
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("create","lpc");
// bool = true;
// Log.d("insert","true" + bool);
} else {
}
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
}
}
else if(jsonObject == null){
Log.d("null", "null1");
//bool = false;
}
return null;
}
protected void onPostExecute(boolean bool){
if(bool == false)
Log.d("Insertion failed", "ID already inserted");
}
}
/* public void Getallcontacts()
{
ContentResolver resolver;
Cursor c = getContentResolver().query(
Data.CONTENT_URI,
null,
Data.HAS_PHONE_NUMBER + "!=0 AND (" + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=?)",
new String[]{Email.CONTENT_ITEM_TYPE, Phone.CONTENT_ITEM_TYPE},
Data.CONTACT_ID);
while (c.moveToNext()) {
long id = c.getLong(c.getColumnIndex(Data.CONTACT_ID));
String name = c.getString(c.getColumnIndex(Data.DISPLAY_NAME));
String data1 = c.getString(c.getColumnIndex(Data.DATA1));
System.out.println(id + ", name=" + name + ", data1=" + data1);
}
}*/
/**
* This interface callback lets the main contacts list fragment notify
* this activity that a contact has been selected.
*
* #param contactUri The contact Uri to the selected contact.
*/
public void onContactSelected(Uri contactUri) {
if (isTwoPaneLayout && mContactDetailFragment != null) {
// If two pane layout then update the detail fragment to show the selected contact
mContactDetailFragment.setContact(contactUri);
} else {
// Otherwise single pane layout, start a new ContactDetailActivity with
// the contact Uri
Intent intent = new Intent(this, ContactDetailActivity.class);
intent.setData(contactUri);
startActivity(intent);
}
}
/**
* This interface callback lets the main contacts list fragment notify
* this activity that a contact is no longer selected.
*/
public void onSelectionCleared() {
if (isTwoPaneLayout && mContactDetailFragment != null) {
mContactDetailFragment.setContact(null);
}
}
#Override
public boolean onSearchRequested() {
// Don't allow another search if this activity instance is already showing
// search results. Only used pre-HC.
return !isSearchResultView && super.onSearchRequested();
}
you need create one class for your purpose like following:
public class Contact()
{
private String _name , _phoneNum , _email , _id;
public Contact(String id , String name , String phoneNum , String emailAdd)
{
_name = name;
_phoneNum = phoneNum;
_id = id;
_email = emailAdd;
}
public void SetName(String name)
{
_name = name;
}
public String GetName()
{
return _name;
}
// other getter and setter
}
and for passing to your AsyncTask use:
ArrayList<Contact> contacts = new ArrayList<Contact>()
// add this two line and do this for all your obj
Contact contact = new Contact(id , name , phoneNumber , emailAddress);
contacts.add(contact);
// after putting all data to contacts do following code
TestAsyncTask task= new TestAsyncTask();
task.execute(contacts);
and AsyncTask class:
class TestAsyncTask extends AsyncTask<ArrayList<Contact>, Void, Void>{
#Override
protected Void doInBackground(ArrayList<Contact>... params) {
// TODO Auto-generated method stub
ArrayList<Contact> contactArray = params[0];
return null;
}
}
While declaring the AsyncTask in your class , declare it as follow :
class TestAsyncTask extends AsyncTask<String[], Void, Void>{
#Override
protected Void doInBackground(String[]... params) {
// TODO Auto-generated method stub
String[] strArray = params[0];
return null;
}
}
The first parameter for the accepts the parameter you want to pass to the Asynctask created by you.
Also, call it as :
new TestAsyncTask().execute(myStringArray);
Create an array list like
ArrayList<SavingContact> contactList = new ArrayList<SavingContact>();
and when you are adding into model object add that object tnto array list like
savingcontacts.savingcontact(id, name, phone, email);
contactList.add(savingcontacts);
and then pass this arraylist in constructor of your asyntask class.
Create a object "Contact" and fillt it with set and get method for ID, NAME, PHONE, and EMAIL.
public class Contact()
{
private String _name;
public void setName(String name)
{
_name = name;
}
public String getName()
{
return _name;
}
[...]
}
Store all your contacts in a List:
List<Contact> contacts = new ArrayList<Contact>()
Send your list to your AsyncTask
Best You Can use like this
class TestAsyncTask extends AsyncTask<ArrayList<String>, Void, Void>{
#Override
protected Void doInBackground(ArrayList<String>... params) {
// TODO Auto-generated method stub
for(int i =0 ; i<params.size();i++)
{
String Str = params.get(i);
}
return null;
}
}
you can use like that,its easy way to store values to Array and also get values

Categories

Resources