I am working on an android code and trying to update the user information. I am able to retrieve the information but have not been able to update. Not sure what I am doing wrong.
In the if-else statement, it does not hit the If statement, goes directly to the error(else statement.
here is the code
package com.example.autrui;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SendCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditPP extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editpp);
final Button confirmChangeEditPP = (Button) findViewById(R.id.bconfirmChangeEditPP);
final EditText fullName = (EditText) findViewById(R.id.etFullName);
final EditText email = (EditText) findViewById(R.id.etEmail);
//final ParseUser currentUser = new ParseUser();
final ParseUser currentUser = ParseUser.getCurrentUser();
System.out.println(currentUser);
String objectId = currentUser.getObjectId();
System.out.println(objectId);
String fName = currentUser.getString("fullName");
fullName.setText(fName);
email.setText(currentUser.getString("email"));
ParseQuery<ParseObject> userQuery = ParseQuery.getQuery("User");
userQuery.getInBackground((String)objectId, new GetCallback<ParseObject>(){
public void done(final ParseObject object, ParseException e) {
if (e == null) {
confirmChangeEditPP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
currentUser.setACL(acl);
object.put("fullName", fullName.getText().toString());
object.put("email", email.getText().toString());
object.saveInBackground();
}
});
} else {
Log.e("error","error");
}
}
});
}
#Override
public void onBackPressed() {
finish();
// Go to settings
/*
* if(MainActivity.s.isEmpty()) return; else { View v =
* MainActivity.s.pop(); Class c = MainActivity.s2.pop(); Intent intent
* = new Intent(v.getContext(), c); startActivityForResult(intent, 0); }
*/
}
private void showUserDetailsActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
I got the answer. the error was regarding the ACL and yes we did not need the query. I wrote the whole code again and made it simpler.
Related
Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));
I try have departureCity value (it set in if/else of onItemSelected method in FlightCityOnItemSelectedListener class) in my FlightAct activity (value will use URL to parse json).
Now how can I get departureCity value all of my FlightAct.java ? or other activities?
because I will use many variables out of loops that they are in methods.how use them out of methods?
package ir.safarbazha.safarbazha.Core.adapter;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
public class FlightCityOnItemSelectedListener
implements AdapterView.OnItemSelectedListener {
String departureCity;
public void onItemSelected(
AdapterView<?> parent,
View view,
int pos,
long id
) {
String selectedCity = parent.getItemAtPosition(pos).toString();
if (selectedCity.equals("آبادان")) {
departureCity="ABD";
Toast.makeText(parent.getContext(),
"آنچه انتخاب شد : " +
parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
================================================================================
package ir.safarbazha.safarbazha.Acts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.adapter.FlightCityOnItemSelectedListener;
import ir.safarbazha.safarbazha.R;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class FlightAct extends AppCompatActivity {
Context currentActivity=FlightAct.this;
ActionBar mainActionbar;
ImageView mainToolbarMenu;
ImageView mainToolbarHome;
ImageView mainToolbarAbout;
ImageView mainToolbarAccount;
ImageView mainToolbarSearch;
DrawerLayout mainDLayout;
DrawerCustomListAdapter mainDCLAdapter;
String[] mainDitems;
List<String> mainDItems;
ListView mainDLV;
//Just For This Activity...
Spinner departureCity , arrivalCity;
TextView departureDate , arrivalDate , capacityCount;
RadioButton radioButtonOneWayFlightType , radioButtonRoundTripFlightType;
Button btnSubmitFlightForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")){
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_flight);
}
setContentView(R.layout.act_flight);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainActionbar=getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
mainActionbar.setCustomView(v);
mainActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu=(ImageView)findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mainDLayout.isDrawerOpen(GravityCompat.START))
mainDLayout.closeDrawer(GravityCompat.START);
else mainDLayout.openDrawer(GravityCompat.START);
}
});
//Main ToolBar Home Image Object...
mainToolbarHome=(ImageView)findViewById(R.id.toolbar_home_icon);
mainToolbarHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,HomeAct.class));
}
});
//Main ToolBar About Image Object...
mainToolbarAbout=(ImageView)findViewById(R.id.toolbar_about_icon);
mainToolbarAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,AboutAct.class));
}
});
//Main ToolBar Account Image Object...
mainToolbarAccount=(ImageView)findViewById(R.id.toolbar_account_icon);
mainToolbarAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,AccountAct.class));
}
});
//Main ToolBar Search Image Object...
mainToolbarSearch=(ImageView)findViewById(R.id.toolbar_search_icon);
mainToolbarSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(currentActivity,SearchAct.class));
}
});
//Set Custom Navigation Drawer...
mainDLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mainDLV=(ListView)findViewById(R.id.drawer_lv);
mainDitems= getResources().getStringArray(R.array.main_titles);
mainDItems=new ArrayList<String>(Arrays.asList(mainDitems));
mainDCLAdapter=new DrawerCustomListAdapter(this,mainDItems);
mainDLV.setAdapter(mainDCLAdapter);
mainDLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = getResources().getStringArray(R.array.main_titles)[position];
if (position==0)
startActivity(new Intent(currentActivity, HomeAct.class));
else if (position == 1)
startActivity(new Intent(currentActivity,AboutAct.class));
else if (position == 2)
startActivity(new Intent(currentActivity, PostAct.class));
else if (position == 3)
Snackbar.make(view, "کاربر گرامی شما هم اکنون در *پرواز ها* برنامه سفر باز ها هستید!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
else if (position == 4)
startActivity(new Intent(currentActivity, ProductAct.class));
else if (position == 5)
startActivity(new Intent(currentActivity, AccountAct.class));
else if (position == 6)
startActivity(new Intent(currentActivity, ContactAct.class));
}
});
//Just For This Activity...
addListenerOnButton();
addListenerOnSpinnerItemSelection();
//Selected Departure And Arrival Airports...
departureCity=(Spinner)findViewById(R.id.departure_city);
arrivalCity=(Spinner)findViewById(R.id.arrival_city);
//Selected Flight Type (OneWay or RoundTrip)...
radioButtonOneWayFlightType=(RadioButton)findViewById(R.id.btnRadioOneWayFlightType);
radioButtonRoundTripFlightType=(RadioButton)findViewById(R.id.btnRadioRoundTripFlightType);
radioButtonOneWayFlightType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrivalDate.setVisibility(View.GONE);
}
});
radioButtonRoundTripFlightType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrivalDate.setVisibility(View.VISIBLE);
}
});
//Selected Departure And Arrival Date...
departureDate=(TextView)findViewById(R.id.departure_date);
arrivalDate=(TextView)findViewById(R.id.arrival_date);
//Selected Count Of Capacity...
capacityCount=(TextView)findViewById(R.id.capacity_count);
}
//Set Custom Font For All Views in Core/app/AppController ...
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
//Just For This Activity...
//DropDown City Choosing...
public void addListenerOnSpinnerItemSelection() {
departureCity = (Spinner) findViewById(R.id.departure_city);
arrivalCity = (Spinner)findViewById(R.id.arrival_city);
departureCity.setOnItemSelectedListener(new FlightCityOnItemSelectedListener());
arrivalCity.setOnItemSelectedListener(new FlightCityOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
departureCity = (Spinner) findViewById(R.id.departure_city);
arrivalCity = (Spinner) findViewById(R.id.arrival_city);
btnSubmitFlightForm = (Button) findViewById(R.id.btnSubmitFlightActForm);
btnSubmitFlightForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(currentActivity,"OnClickListener : "
+"\nشهر مبدا : "+
String.valueOf(departureCity.getSelectedItem())
+
"\nشهر مقصد : "+
String.valueOf(arrivalCity.getSelectedItem())
,
Toast.LENGTH_SHORT).show();
}
});
}
}
Save the required data in a class variable.
You can use a bundle to send the data to other activities from which you can access that data.
Code example to store the data in the intent used to launch the second activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putString("stringvalue", strValue);
b.putLong("longvalue", lngValue);
b.putDouble("doublevalue", doubValue);
b.putBoolean("boolvalue", boolValue);
intent.putExtras(b);
startActivity(intent);
Code to get the data from the bundle in the second activity (this code to be placed in the onCreate() method):
// get the Intent that started this Activity
Intent in = getIntent();
Bundle b = in.getExtras();
String strValue= b.getString("stringvalue");
long longValue = b.getLong("longvalue");
double doubleValue= b.getDouble("doublevalue");
boolean boolValue= b.getBoolean("boolvalue");
You can make it static ,so you can use it anywhere in your other classes.
change "public static String departureCity" instead of "String departureCity";
then you can call it like that : FlightCityOnItemSelectedListener.departureCity
(without instantiate FlightCityOnItemSelectedListener).
I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking
In my example, i am entering mobile no., message content in one activity. Before leaving that activity i am saving that info in "Shared Preference". In other activity i am trying to get those mob no,message,i am able to get no but unable to getting that message(second value).please help me to solve the issue.
DefaultDetails.java
package com.example.nirbhaya;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DefaultDetails extends Activity implements OnClickListener{
Button save,reset;
EditText dMob,dMsg,dEmail;
String defMobNo,defMsg,defEmail;
SharedPreferences DefaultData;
private static final String TAG = "DD-Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.defaultdetails);
initializing();
}
private void initializing() {
// TODO Auto-generated method stub
save = (Button)findViewById(R.id.bsave1);
reset = (Button)findViewById(R.id.bReset);
dMob = (EditText)findViewById(R.id.etDefMobNo);
dMsg = (EditText)findViewById(R.id.etDefMsg);
dEmail = (EditText)findViewById(R.id.etDefEmail);
save.setOnClickListener(this);
reset.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.bsave1:
defMobNo = dMob.getText().toString();
defMsg = dMsg.getText().toString();
defEmail = dEmail.getText().toString();
Log.i(TAG,"DONE");
DefaultData = getSharedPreferences("defMobileNo",0);
SharedPreferences.Editor store = DefaultData.edit();
store.putString("defMobileNo", defMobNo);
store.putString("defMessgae", defMsg);
store.putString("defEMail", defEmail);
store.commit();
Intent openStartingPoint = new Intent (getApplicationContext(), CurrentDetails.class);
startActivity(openStartingPoint);
break;
case R.id.bReset:
((EditText) findViewById(R.id.etDefMobNo)).setText("");
((EditText) findViewById(R.id.etDefEmail)).setText("");
((EditText) findViewById(R.id.etDefMsg)).setText("");
break;
}
}
}
DefSMS.java
package com.example.nirbhaya;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DefSms extends Activity{
Button buttonSend;
String defNo,defMsg;
SharedPreferences DefaultData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.defsms);
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
DefaultData = getSharedPreferences("defMessgae",0);
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(defNo, null, defMsg, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
Here def no getting message as Couldn't load data
please help me
Replace with this:
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
This is how basically sharedpreference work
To Store the values
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","myNameisnothing");
editor.commit();
To get the values
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String name = prfs.getString("Name", "");
This way it'd return the value of the name as myNameisnothing.
PS.Correct me if im wrong.
You are wrongly using
DefaultData = getSharedPreferences("defMessgae",0); in DefSMS.java
Please remove this and it will work fine.
You were trying to get shared preference named defMessgae which doesnot even exist. So when you try to access it, android will create a new preference with default value. That is why you were getting "Couldn't load data"
When i call the purchase screen i can buy the in app product and everything works ok but when the user leave the app and returns to view the product it keeps asking them to buy again,
I need to know how i can make this so when the user purchases the app the store screen doesnt come up anymore and they can access the product, the app is designed so that when the user buys the app they gain access to a new activity with features built in
if anyone could help, I would be most grateful
I used this tutorial which was very helpful in getting me started:[TUT] Simple InApp Billing / Payment By blundell
Here is my code
package com.IrishSign.app;
import java.util.Locale;
import com.IrishSign.app.BillingHelper;
import com.IrishSign.app.R;
import com.IrishSign.app.BillingService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class IrishSignAppActivity extends Activity implements OnClickListener {
private static final String TAG = "BillingService";
private Context mContext;
private ImageView purchaseableItem;
private Button purchaseButton;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("BillingService", "Starting");
setContentView(R.layout.main);
mContext = this;
Button A = (Button) findViewById(R.id.alphabet);
Button purchaseableItem = (Button) findViewById(R.id.topics);
Button Intro = (Button) findViewById(R.id.intro);
Button G = (Button) findViewById(R.id.about);
purchaseableItem.setOnClickListener(this);
startService(new Intent(mContext, BillingService.class));
BillingHelper.setCompletedHandler(mTransactionHandler);
A.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent1 = new Intent("com.IrishSign.app.alpha");
startActivity(intent1);
}
});
Intro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("com.IrishSign.app.Intro");
startActivity(intent1);
}
});
G.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog alertDialog = new AlertDialog.Builder(
IrishSignAppActivity.this).setCancelable(false)
.create(); // Reads Update
alertDialog.setTitle("Welcome");
alertDialog.setMessage("-----");//
alertDialog.setButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
Intent intent5 = new Intent(
IrishSignAppActivity.this,
IrishSignAppActivity.class);
}
});
alertDialog.show(); // <-- Shows dialog on screen.
}
});
}
public Handler mTransactionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Log.i(TAG, "Transaction complete");
Log.i(TAG, "Transaction status: "
+ BillingHelper.latestPurchase.purchaseState);
Log.i(TAG, "Item purchased is: "
+ BillingHelper.latestPurchase.productId);
if (BillingHelper.latestPurchase.isPurchased()) {
Intent intent = new Intent("com.IrishSign.app.Topics");
startActivity(intent);
}
};
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.topics:
if (BillingHelper.isBillingSupported()) {
BillingHelper.requestPurchase(mContext,
"com.blundell.item.passport");
// android.test.purchased or android.test.canceled or
// android.test.refunded or com.blundell.item.passport
} else {
Log.i(TAG, "Can't purchase on this device");
purchaseButton.setEnabled(false); // XXX press button before
// service started will
// disable when it shouldnt
}
break;
default:
// nada
Log.i(TAG, "default. ID: " + v.getId());
break;
}
}
#Override
protected void onPause() {
Log.i(TAG, "onPause())");
super.onPause();
}
#Override
protected void onDestroy() {
BillingHelper.stopService();
super.onDestroy();
}
}
You can check when the application starts by using restoreTransactions. If you have used Managed Products or Subscriptions then only you will get all the details of the user.
For Unmanaged product there is no detail maintained by google.
So call this in your main activity
mBillingService = new BillingService();
mBillingService.setContext(this);
mBillingService.restoreTransactions();
Once you call this in ResponseHandler class there is one method purchaseResponse
purchaseResponse(final Context context,
final PurchaseState purchaseState, final String productId,
final String orderId, final long purchaseTime,
final String developerPayload, final String purchaseToken) {
}
which will return all the details.
You can check purchaseState then after
if (purchaseState == PurchaseState.PURCHASED) {
} else if (purchaseState == PurchaseState.REFUNDED) {
} else if (purchaseState == PurchaseState.CANCELED) {
}