I have just started Android and i am working on Simple Login Page,where user can use their email and password to login with some conditions while login. When user login as a "store owner",his name and email is shown on the next page (i.e on the Fragment class) which is working fine but whenever user login as a "public user",his name and email is not showing on the next page.
Note: I am using webservices and SharedPreferences to fetch and save data.
Thanks in Advance
Here is my code
LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
EditText login_emailid, login_password;
String str_login_email, str_login_password;
Button login_button;
public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_button = (Button) findViewById(R.id.loginBtn);
login_emailid = (EditText) findViewById(R.id.login_emailid);
login_password = (EditText) findViewById(R.id.login_password);
login_button = (Button) findViewById(R.id.loginBtn);
login_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == login_button) {
str_login_email = login_emailid.getText().toString();
str_login_password = login_password.getText().toString();
if (str_login_email.isEmpty()) {
login_emailid.setError("Enter your email");
} else if (str_login_password.isEmpty()) {
login_password.setError("Password Please");
} else {
new AsyncTaskRunner().execute();
}
}
}
}
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public String connection(String action) {
String result = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://beta.gkninternational.life/webservice/user_login.php");// replace with your url
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair(
"action", action));
nameValuePairList.add(new BasicNameValuePair(
"Email", str_login_email));
nameValuePairList.add(new BasicNameValuePair(
"Password", str_login_password));
try {
Log.e("nameValuePairList", " " + nameValuePairList);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient
.execute(httpPost);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
result = stringBuilder.toString();
Log.e("result", stringBuilder.toString());
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("First Exception coz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second Exception coz of HttpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return result;
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog mProgressBar;
String resp;
int success;
String message;
String name, email, password, userrole, userpic, iddd;
String storeId,storeName;
SharedPreferences sharedPreferencesLogin;
SharedPreferences.Editor editor;
#Override
protected String doInBackground(String... params) {
String result = connection("Login_Activity");
try {
sharedPreferencesLogin = getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
editor = sharedPreferencesLogin.edit();
JSONObject jsonObject = new JSONObject(result);
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
iddd = jsonObject.getString("UserId");
name = jsonObject.getString("FirstName");
email = jsonObject.getString("Email");
userrole = jsonObject.getString("UserRole");
storeId = jsonObject.getString("StoreId");
storeName = jsonObject.getString("StoreName");
editor.putString("UserId", name);
editor.putString("FirstName", name);
editor.putString("Email", email);
editor.putString("userrole", userrole);
editor.putString("storeIdLogin", storeId);
editor.putString("StoreNameLogin", storeName);
editor.apply();
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
mProgressBar.dismiss();
if (success == 2) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
} else if (success == 1) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
if(userrole.equals("store_owner"))
{
if(storeName.equals("Dummy")){
startActivity(new Intent(LoginActivity.this, EditActivity.class));
finish();
}
else{
Intent intentt = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intentt);
finish();
}
}
else{
Intent intentuser = new Intent(LoginActivity.this, AfterSplash.class);
startActivity(intentuser);
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressBar = new ProgressDialog(LoginActivity.this);
mProgressBar.setMessage("Connecting to server");
mProgressBar.setCancelable(false);
mProgressBar.show();
}
}
Frament class
public class MyFragment extends Fragment{
SharedPreferences sharedPreferencesLogin;
public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
TextView names,emails;
String str_names,str_emails;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_my, container, false);
sharedPreferencesLogin= getActivity().getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
names=(TextView)layout.findViewById(R.id.names);
emails=(TextView)layout.findViewById(R.id.emails);
str_names= sharedPreferencesLogin.getString("FirstName","");
str_emails= sharedPreferencesLogin.getString("Email","");
names.setText(str_names);
emails.setText(str_emails);
}
}
try this to set Shared Pref
String userId=yourstring;
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(youractivity.this);
Editor edit = settings.edit();
edit.putString("name", userId);
settings.commit;
to get shared pref
SharedPreferences settins = PreferenceManager
.getDefaultSharedPreferences(Youractivity.this);
name=settings.getString("name", "anon");
You have to use a bundle and a serializable object to pass.:
From the activity:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(ARGUMENT_KEY, objectSerializable);
fragment.setArguments(bundle); showFragment(fragment)
On the fragment:
Bundle bundle = this.getArguments();
if (bundle != null) {
Object neededObject = bundle.getSerializable(ser_key)
}
Override newInstance() method in your fragment like this.
public static YourFragment newInstance(Bundle bundle) {
ActivityFeedListFragment fragment = new ActivityFeedListFragment();
fragment.setArguments(bundle);
return fragment;
}
And pass bundle object.
Related
I searched all forums and solutions but none did the trick. I have an app that scans some text and receive the scan text and show it. This is the file where I get the scan results:
#Override
public void extractData(RomaniaIdFrontRecognizer.Result result) {
super.extractData(result);
savePreferences("selected", result.getLastName());
add(R.string.PPLastName, result.getLastName());
add(R.string.PPFirstName, result.getFirstName());
add(R.string.PPIdentityCardNumber, result.getCardNumber());
add(R.string.PPSeries, result.getIdSeries());
add(R.string.PPCNP, result.getCnp());
add(R.string.PPNationality, result.getNonMRZNationality());
add(R.string.PPPlaceOfBirth, result.getPlaceOfBirth());
add(R.string.PPAddress, result.getAddress());
add(R.string.PPIssuingAuthority, result.getIssuedBy());
add(R.string.PPSex, result.getNonMRZSex());
add(R.string.PPValidFrom, result.getValidFrom());
add(R.string.PPValidUntil, result.getValidUntil());
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = mContext.getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
This part is being executed because if I put a toast, the message shows.
And this is the file where I would want to receive the variable sent with sharedpreferences:
public class ResultActivity extends FragmentActivity implements
ResultFragment.IResultFragmentActivity,
FieldByFieldResultFragment.IFieldByFieldResultFragmentActivity {
String a;
String TempName, TempEmail ;
String e;
Bitmap bitmap;
ByteArrayOutputStream baos;
byte[] imageInByte;
private LayoutInflater mInflater;
Toast toast;
LoginDataBaseAdapter loginDataBaseAdapter;
EditText nume;
EditText prenume;
EditText nr;
EditText serie;
EditText cnp;
EditText nationalitate;
EditText loc;
EditText adresa;
EditText emis;
EditText sex;
EditText start;
EditText stop;
String usern;
public static final String EXTRAS_RESULT_TYPE = "EXTRAS_RESULT_TYPE";
public enum ResultType {
RECOGNIZER_BUNDLE,
FIELD_BY_FIELD_BUNDLE
}
protected ViewPager mPager;
protected RecognizerBundle mRecognizerBundle;
protected FieldByFieldBundle mFieldByFieldBundle;
protected ResultType mResultType;
private ArrayList<Recognizer> mRecognizersWithResult;
#SuppressLint("InlinedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActivityContentView();
// loginDataBaseAdapter=new LoginDataBaseAdapter(getApplicationContext());
// loginDataBaseAdapter=loginDataBaseAdapter.open();
// String aa=loginDataBaseAdapter.getMagazin();
String s = loadPreferences("selected");
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_LONG).show();
Intent intent = getIntent();
mResultType = (ResultType) intent.getSerializableExtra(EXTRAS_RESULT_TYPE);
mRecognizerBundle = new RecognizerBundle();
mFieldByFieldBundle = new FieldByFieldBundle();
if (mResultType == null) {
if (mRecognizerBundle.existsInIntent(intent)) {
mResultType = ResultType.RECOGNIZER_BUNDLE;
} else if (mFieldByFieldBundle.existsInIntent(intent)) {
mResultType = ResultType.FIELD_BY_FIELD_BUNDLE;
}
}
if (mResultType == null) {
throw new IllegalStateException("Results must be passed to ResultActivity!");
}
mPager = findViewById(R.id.resultPager);
switch (mResultType) {
case RECOGNIZER_BUNDLE:
mRecognizersWithResult = new ArrayList<>();
mRecognizerBundle.loadFromIntent(intent);
for ( Recognizer< Recognizer, Recognizer.Result > r : mRecognizerBundle.getRecognizers() ) {
if ( r.getResult().getResultState() != Recognizer.Result.State.Empty ) {
mRecognizersWithResult.add( r );
// String text = mRecognizersWithResult.get(0).toString();
// Toast.makeText(getApplicationContext(), text,Toast.LENGTH_LONG).show();
}
}
mPager.setAdapter(new RecognizerListFragmentAdapter(getSupportFragmentManager()));
break;
case FIELD_BY_FIELD_BUNDLE:
// mFieldByFieldBundle.loadFromIntent(intent);
// mPager.setAdapter(new FieldByFieldBundleFragmentAdapter(getSupportFragmentManager()));
// break;
}
TabPageIndicator indicator = findViewById(R.id.resultIndicator);
indicator.setViewPager(mPager);
indicator.setClipChildren(false);
}
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mResultType == ResultType.RECOGNIZER_BUNDLE) {
mRecognizerBundle.saveState();
} else if (mResultType == ResultType.FIELD_BY_FIELD_BUNDLE) {
mFieldByFieldBundle.saveState();
}
}
public void setActivityContentView() {
setContentView(R.layout.result_menu);
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences =getApplicationContext().getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
#Override
public Recognizer< Recognizer, Recognizer.Result > getRecognizerAtPosition(int resultPosition) {
if (resultPosition < 0 || resultPosition >= mRecognizersWithResult.size()) {
throw new IllegalStateException("Recognizer with non empty result on requested position"
+ " does not exist. Possible cause is that recognizer bundle state has been lost"
+ " in intent transactions.");
}
//noinspection unchecked
return mRecognizersWithResult.get(resultPosition);
}
#Override
public FieldByFieldBundle getFieldByFieldBundle() {
return mFieldByFieldBundle;
}
private class RecognizerListFragmentAdapter extends FragmentPagerAdapter {
RecognizerListFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ResultFragment.newInstance(position);
}
#Override
public int getCount() {
return mRecognizersWithResult.size();
}
#Override
public CharSequence getPageTitle(int position) {
return ResultUtils.getRecognizerSimpleName(mRecognizersWithResult.get(position));
}
}
private class FieldByFieldBundleFragmentAdapter extends FragmentPagerAdapter {
FieldByFieldBundleFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FieldByFieldResultFragment.newInstance();
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
return ResultActivity.this.getString(R.string.title_field_by_field_results);
}
}
public void footerButtonClickHandler(View view) {
// String sessionId= getIntent().getStringExtra("test");
// Toast.makeText(getApplicationContext(), "da", Toast.LENGTH_LONG).show();
// new RegisterAsyntaskNew().execute();
ImageView img=(ImageView) findViewById(R.id.resultValueee);
// img.buildDrawingCache();
// Bitmap bitmap = img.getDrawingCache();
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = drawable.getBitmap();
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
// RomanianIDFrontSideRecognitionResultExtractor myActivity2 = new RomanianIDFrontSideRecognitionResultExtractor();
// myActivity2.InsertData();
Img(imageInByte,e);
// InsertData(nume.getText().toString(), prenume.getText().toString(), nr.getText().toString(), serie.getText().toString(),cnp.getText().toString(),nationalitate.getText().toString(), loc.getText().toString(),adresa.getText().toString(),emis.getText().toString(),sex.getText().toString(),start.getText().toString(),stop.getText().toString(),usern);
finish();
}
public void InsertData(final String nume, final String prenume, final String nr, final String serie, final String cnp, final String nationalitate
, final String locn, final String adresa, final String emis, final String sex, final String start, final String sfarsit,final String username){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = nume ;
String pren = prenume ;
String nr1 = nr;
String serie1 = serie ;
String cnp1 = cnp ;
String nat = nationalitate ;
String locn1 = locn ;
String adresa1 = adresa ;
String emis1 = emis ;
String sex1 = sex ;
String start1 = start ;
String sfarsit1 = sfarsit ;
String user1 = username ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", pren));
nameValuePairs.add(new BasicNameValuePair("nr", nr1));
nameValuePairs.add(new BasicNameValuePair("serie", serie1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
nameValuePairs.add(new BasicNameValuePair("nat", nat));
nameValuePairs.add(new BasicNameValuePair("locn", locn1));
nameValuePairs.add(new BasicNameValuePair("adresa", adresa1));
nameValuePairs.add(new BasicNameValuePair("emis", emis1));
nameValuePairs.add(new BasicNameValuePair("sex", sex1));
nameValuePairs.add(new BasicNameValuePair("start", start1));
nameValuePairs.add(new BasicNameValuePair("sfarsit", sfarsit1));
nameValuePairs.add(new BasicNameValuePair("username", user1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
toast = Toast.makeText(ResultActivity.this, a, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.parseColor("#66ff33"));
int toastDuration = 5000;
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(toastDuration, 1000) {
public void onTick(long millisUntilFinished) {
toast.show();
}
public void onFinish() {
toast.cancel();
}
};
toast.show();
countDownTimer.start();
}
});
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(nume, prenume,nr,serie,cnp,nationalitate,locn,adresa,emis,sex,start,sfarsit,username);
}
public void Img(final byte[] data,final String cnpimg){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String cnp1 = cnpimg ;
Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://promotii.grupsapte.ro/php/scanid/img.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
// ResultActivity.this.runOnUiThread(new Runnable() {
// public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
// }
// });
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}
}
The send-receive variable with shared preferences worked but now, i don't know the cause, first time I get a null variable and if I try it again then I receive what I scan first. So, the variable is shown only the second time with the value scan for the first time. Even if I try to put a simple text and send it, it will show only the second time I make the action. But I repeat, the file is getting executed because if I put a toast, it will show. I think that the receiving of the shared preferences variable is done first and then the code from the first file is being executed. I tried to put the code in oncreate, onresume but nothing did the trick. Any help would be much appreciated.
The solution for me was to put a delay of 1 second for the process of receiving thorugh shared preferences. See below:
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
ResultActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
String a = loadPreferences("nume");
String b= loadPreferences("prenume");
String c= loadPreferences("nr");
String d= loadPreferences("serie");
e= loadPreferences("cnp");
String f= loadPreferences("nationalitate");
String g= loadPreferences("locn");
String h= loadPreferences("adresa");
String i= loadPreferences("emis");
String j= loadPreferences("sex");
String k= loadPreferences("start");
String l= loadPreferences("sfarsit");
usern= "";
String s = Normalizer.normalize(f, Normalizer.Form.NFD);
String bla = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String t = Normalizer.normalize(h, Normalizer.Form.NFD);
String bla1 = t.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String a1 = Normalizer.normalize(a, Normalizer.Form.NFD);
String bla2 = a1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String b1 = Normalizer.normalize(b, Normalizer.Form.NFD);
String bla3 = b1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String g1 = Normalizer.normalize(g, Normalizer.Form.NFD);
String bla4 = g1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
nume = (EditText) findViewById(R.id.nume);
nume.setText(bla2);
prenume = (EditText) findViewById(R.id.prenume);
prenume.setText(bla3);
nr = (EditText) findViewById(R.id.nrserie);
nr.setText(c);
serie = (EditText) findViewById(R.id.serie);
serie.setText(d);
cnp = (EditText) findViewById(R.id.cnp);
cnp.setText(e);
nationalitate = (EditText) findViewById(R.id.nationalitate);
nationalitate.setText(bla);
loc = (EditText) findViewById(R.id.loc);
loc.setText(bla4);
adresa = (EditText) findViewById(R.id.adresa);
adresa.setText(bla1);
emis = (EditText) findViewById(R.id.emis);
emis.setText(i);
sex = (EditText) findViewById(R.id.sexx);
sex.setText(j);
start = (EditText) findViewById(R.id.start);
start.setText(k);
stop = (EditText) findViewById(R.id.stop);
stop.setText(l);
// String s = loadPreferences("selected");
// Toast.makeText(getApplicationContext(), a,Toast.LENGTH_LONG).show();
}
});
}
}, 1000); // End of your timer code.
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}
I have android app for login, when user gives login details that data have to pass in multiple activities.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username=(EditText)findViewById(R.id.user_name);
passwrd=(EditText)findViewById(R.id.Pass_word);
login=(Button)findViewById(R.id.Login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = username.getText().toString();
String password = passwrd.getText().toString();
new Mytask().execute(email, password);
}
});
}
I want to pass email and password to multiple activities..
I just tried Bundle.
I stored email value as "name".
And i just passed the value to another activity(Below code).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testpage);
Entertext = (EditText) findViewById(R.id.tex_id);
Submit = (Button) findViewById(R.id.sub_mit);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Text = Entertext.getText().toString();
Intent i = getIntent();
Bundle b = i.getBundleExtra("personBdl");
String name = b.getString("name");
new Mytask().execute(name,Text);
}
});
private class Mytask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
StringBuilder dta = null;
try {
URL url = new URL("http://xxxyyy.com/insert.php?user=" + params[0] + "&value=" + params[1]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
} else {
//Handle else
}
return dta.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
Email has passed as "name"(bundle).
"name" value passed as params[0] to my php file.
But params[0] not passed to my php file.
Could you please help me with this. Thank you.
You should probably use SharedPreferences instead of Bundle.
Save data like this:
SharedPreferences sPref;
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString("email", etText.getText().toString());
ed.putString("password", etText.getText().toString());
ed.commit();
And get it in your activities like this:
sPref = getPreferences(MODE_PRIVATE);
String email = sPref.getString("email", "");
String password = sPref.getString("password", "");
etText.setText(savedText);
And I also recommend you to use it in separate thread.
In my project , to access the webservice am using http class which is not working properly and my project stops.
Can someone tell me an alternate way for accessing the webservice instead of using http.
Thank you in advance
class httpclass {
String result;
public String server_conn(String user_url)
{
// String user_url="";
String user_url3=user_url.replaceAll(" ","%20");
String user_url2=user_url3.replaceAll("\n","%0D");
HttpClient client = new DefaultHttpClient();
HttpGet siteRequest = new HttpGet(user_url2);
StringBuilder sb = new StringBuilder();
HttpResponse httpResponse;
try {
httpResponse = client.execute(siteRequest);
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
String line = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
log in form
public class LoginForm extends FragmentActivity {
/** Called when the activity is first created. */
TextView txt1, txt2, err,forget;
EditText name;
EditText pass;
Button click,vend;
CheckBox savepass;
Button newuser;
Button signin;
#SuppressWarnings("unused")
private Cursor signin1;
SharedPreferences sharedPreferences=null;
public static String str1, str2;
public static String result;
public static String username;
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, "68640bea");
setContentView(R.layout.login);
vend=(Button)findViewById(R.id.vend);
name = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
savepass=(CheckBox)findViewById(R.id.savepass);
Button cancel = (Button) findViewById(R.id.cancel);
//Button back = (Button) findViewById(R.id.back);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent second = new Intent( LoginForm.this,canceluser.class);
startActivity(second);
finish();
}
});
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
String name1=sharedPreferences.getString("p_name", "");
name.setText(name1.toString());
String pass1=sharedPreferences.getString("p_pass", "");
pass.setText(pass1.toString());
//s forget=(TextView)findViewById(R.id.forget);
signin = (Button) findViewById(R.id.signin);
click = (Button) findViewById(R.id.click);
newuser = (Button) findViewById(R.id.signup);
vend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
startActivity(viewIntent);
}});
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
startActivity(intent1);
finish();
}});
signin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(name.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Username");
name.requestFocus();
}
else if(pass.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Password");
pass.requestFocus();
}
else
{
str1 = name.getText().toString();
str2 = pass.getText().toString();
boolean value = false;
// validuser();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
openconn(str1, str2);
}
else
{
alertbox("Message!", "No Internet Connection!");
}
}
}
});
newuser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newuser();
}
});
}
public void openconn(String strr1, String strr2)
{
if (!strr1.equals("") && !strr2.equals(""))
{
err = (TextView) findViewById(R.id.err);
// String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
// alertbox("",""+result);
if (result != null)
{
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if (result.equals("InvalidUser "))
{
Dialog locationError = new AlertDialog.Builder(
LoginForm.this).setIcon(0).setTitle("Message!")
.setPositiveButton(R.string.yes, null).setMessage(
"Sorry, Invalid Username or Password ")
.create();
locationError.show();
name.requestFocus();
}
else if(result.equals(strr1))
{
// Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();
if(savepass.isChecked())
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name",name.getText().toString());
//editor.putString("p_pass",pass.getText().toString());
editor.commit();
}
else
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name", "");
editor.putString("p_pass","");
editor.commit();
}
validuser();
}
else
{
alertbox("Message!","Error in network connection");
}
}
}
}
public void validuser()
{
username=str1;
name.setText("");
pass.setText("");
Intent userintent = new Intent(this, welcomeuser1.class);
//userintent.putExtra("name5",str1);
//Intent userintent=new Intent(this,WeddingInfo.class);
startActivity(userintent);
finish();
}
public void newuser() {
Intent userintent1 = new Intent(this, newuserform.class);
startActivity(userintent1);
finish();
}
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
// // EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
// EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
}
Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk
Path in archive: META-INF/LICENSE.txt
Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda-
time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can ignore those files in your build.gradle:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/LICENSE.txt
File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can do this way:
AsyncTask for Web service:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
Now Get Response from server in Background thread:
public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
InputStream is = null;
String Root_Response = null;
HttpResponse httpResponse;
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
try {
httpClient = new DefaultHttpClient(httpParameters);
url = url.replace(" ", "%20");
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jObjStr));
httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
} else if (method == "GET") {
HttpGet httpGet = new HttpGet(new URI(url));
httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
Root_Response = convertStreamToString(is);
Log.i(tag, Root_Response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (URISyntaxException e) {
e.printStackTrace();
}
return Root_Response;
}
Convert Server's Response to String:
public static String convertStreamToString(InputStream inputStream)
throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
Hope it will help you.
call the method server_conn() inside AsyncTask , and pass the url
private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
server_conn(strings[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
and call the asynctastk using below syntax
new AsyncTaskTest().execute(url);
You are facing NetworkOnMainThread exception all you have to do is add this code :
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
For more details you can check developer site.
how to pass extra data from this activity?
public class DetailActivity extends Activity {
#Override
public void onBackPressed() {
}
#SuppressLint("NextAPI")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Button btnForum = (Button) findViewById(R.id.btnForum);
Button btnKuis = (Button) findViewById(R.id.btnKuis);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
final Button btnLogout = (Button) findViewById(R.id.btnBack);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(DetailActivity.this,MainActivity.class);
startActivity(newActivity);
}
});
btnForum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forum = new Intent(DetailActivity.this, Forum.class); ;
startActivity(forum);
}
});
btnKuis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class); ;
startActivity(kuis);
}
});
}
public void showInfo(){
final TextView tNrp = (TextView)findViewById(R.id.txtNrp);
final TextView tName = (TextView)findViewById(R.id.txtName);
final TextView tSmt = (TextView)findViewById(R.id.txtSmt);
final TextView tStatus = (TextView)findViewById(R.id.txtStatus);
String url = "http://xxx/blabla/getID.php";
Intent intent = getIntent();
String MhsID = intent.getStringExtra("idm");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMhsID", MhsID));
String resultServer = getHttpPost(url,params);
String strMemberID = "";
String strNrp = "";
String strPassword = "";
String strName = "";
String strSmt = "";
String strStatus = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strNrp = c.getString("idm");
strName = c.getString("nama-mahasiswa");
strSmt = c.getString("semester");
strStatus = c.getString("status-mahasiswa");
if(!strMemberID.equals(""))
{
tNrp.setText(strNrp);
tName.setText(strName);
tSmt.setText(strSmt);
tStatus.setText(strStatus);
}
else
{
tNrp.setText("-");
tName.setText("-");
tSmt.setText("-");
tStatus.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
this DetailActivity already have extra data from the previous activity, but i need to pass extra data "idm" to Kuisioner Activity. can anyone teach me how to do that? please this is really important to me :(
Declare String MhsID as class level member field like,
public class DetailActivity extends Activity {
private String MhsID = null;
Now in showInfo get Intent data like,
public void showInfo(){
....
Intent intent = getIntent();
MhsID = intent.getStringExtra("idm");
....
And pass values of MhsID to Kuisioner Activity using putExtra() via Intent as you did in previous activity
btnKuis.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExtra("idm",MhsID);
startActivity(kuis);
}
});
And get String idm in Kuisioner Activity same as this activity.
in DetailActivity.java:
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExta("Key_hossam", "value"); // just add this line
startActivity(kuis);
in Kuisioner.java:
inside the onCreate method just write these lines
Intent intent= getIntent();
Bundle b = intent.getExtras();
if(b!=null)
{
String value =(String) b.get("Key_hossam");
}
}
It is all explained HERE.
Just add this line of code:
intent.putExtra(name, value);
So starting new Kuisioner activity should look like this:
String value = "Example value"
Intent kuis = new Intent(DetailActivity.this, Kuisioner.class);
kuis.putExtra("idm", value);
startActivity(kuis);
If you are working with too many variables, and want to pass data among activities, I suggest make your Activity-variables static , and use with class name, no more maintaining variables.
Note : I assume you are using Fragments, you may come back to activities again n again.
Requesting access to token for second time doesn't work thats why we need to store the token for first time to use it in future reference.Thats what i am trying to do here in Twitter integration using SharedPreference while posting tweet.It works fine for the first time while posting tweet but shows popup in second time showing "You don't have access to appname.Please return to appname to continue signup process".
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
Below is my complete code for TwitterFragment.java
TwitterFragment.java
public class TwitterFragment extends ListFragment {
final static String ScreenName = "IBL_Official";
final static String LOG_TAG = "rnc";
private FragmentActivity myContext;
private ListFragment activity;
private ListView listView;
public static EditText tx1;
private ProgressBar mDialog;
private QuickReturnFrameLayout searchLayout;
Button login;
boolean requestTokenFirstTime = true;
twitter4j.Twitter twitter;
RequestToken requestToken = null;
//static RequestToken requestToken ;
twitter4j.auth.AccessToken accessToken;
String oauth_url,oauth_verifier,profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activity = this;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
downloadTweets();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.twit_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
tx1=(EditText)rootView.findViewById(R.id.postcomment);
mDialog = (ProgressBar) rootView.findViewById(R.id.progress_bar);
searchLayout = (QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout);
listView.setVerticalScrollBarEnabled(false);
((QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout)).attach(listView);
rootView.setVerticalScrollBarEnabled(false);
login = (Button)rootView.findViewById(R.id.postbutton);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""), pref.getString("CONSUMER_SECRET", ""));
login.setOnClickListener(new LoginProcess());
return rootView;
}
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
public class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "AuSSA6AHeCv9gskRhGQjSymCO";
final static String CONSUMER_SECRET = "eyRoYBONVh45V185TBYbbb3i9BpWmmaiv4wLbBYXd7UcZGGaDw";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
public String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(String result) {
mDialog.setVisibility(View.GONE);
searchLayout.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
Twitte twits = jsonToTwitter(result);
System.out.println(result);
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> link = new ArrayList<String>();
ArrayList<String> time = new ArrayList<String>();
String logoimage = "";
String name = "";
String officialname = "";
for (Tweet tweet : twits) {
String[] splitted = tweet.getText().split("http://");
Log.d("splitted", String.valueOf(splitted.length));
data.add(splitted[0]);
if (splitted.length > 1) {
link.add("http://" + splitted[1]);
} else {
link.add("");
}
logoimage = tweet.getUser().getProfileImageUrl();
name = tweet.getUser().getName();
officialname = "# " + tweet.getUser().getScreenName();
time.add(tweet.getDateCreated());
}
//
Bitmap image = null;
try {
URL url = new URL(logoimage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
image = getRoundedShape(image);
} catch (Exception e) {
Log.d("error in image", e.toString());
Log.d("image", logoimage);
}
try {
TwitterAdapter adapter = new TwitterAdapter(getActivity(), data, link, image, time, name, officialname);
listView.setAdapter(adapter);
} catch (Exception e) {
System.out.println("error");
}
}
public Twitte jsonToTwitter(String result) {
Twitte twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitte.class);
} catch (IllegalStateException ex) {
}
}
return twits;
}
public Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
}
}
return auth;
}
public String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
inputStream.close();
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
public String getTwitterStream(String screenName) {
String results = null;
try {
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
String combined = urlApiKey + ":" + urlApiSecret;
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW
);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null
);
return targetBitmap;
}
}
private class LoginProcess implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TokenGet().execute();
}}
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
#Override
protected void onPostExecute(String oauth_url) {
if(oauth_url != null){
Log.e("URL", oauth_url);
auth_dialog = new Dialog(getActivity());
auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(oauth_url);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("oauth_verifier") && authComplete == false){
authComplete = true;
Log.e("Url",url);
Uri uri = Uri.parse(url);
oauth_verifier = uri.getQueryParameter("oauth_verifier");
auth_dialog.dismiss();
new AccessTokenGet().execute();
}else if(url.contains("denied")){
auth_dialog.dismiss();
Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();
}
}
});
auth_dialog.show();
auth_dialog.setCancelable(true);
}else{
Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
SharedPreferences.Editor edit = pref.edit();
edit.putString("ACCESS_TOKEN", accessToken.getToken());
edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
User user = twitter.showUser(accessToken.getUserId());
profile_url = user.getOriginalProfileImageURL();
edit.putString("NAME", user.getName());
edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());
edit.commit();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean response) {
if(response){
progress.hide();
// progress.dismiss();
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, profile);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
else{
auth_dialog.dismiss();
}
}
}
}
I think you may simply want to hang on to the oauth access token after the first attempt (or ask for it by calling twitter.getOAuthAccessToken() ) and reuse it for the second time.
I ran into a similar experience and I found that the twitter4j.Twitter twitter; instance already had an access token associated with this instance from my first attempt. So when I asked for the authentication url from the request token ( oauth_url = requestToken.getAuthorizationURL(); ) and opened it in a webpage I got a message similar to your problem description ( "You don't have access to Please return to to continue the signup process." ).
I think if you wanted to you could also start over by recreating the twitter4j.Twitter instance and the related instance variables (like the RequestToken ). However this would also require you to then do the whole authentication process again with would be repeating the same work you did on the first attempt.