I have the following code with no compilation errors, just resulting in an infinite loop... I don't get where the problem is.
When I click the Button, I want to create an object using the values entered in the edittexts and pass them to another activity. But instead, I get a loop.
Each spinner is populated using a string-array from resources/strings. I had some difficulties getting the values here, because at the spinner spTipUtilizator when "Profesor" is selected, I want spGrupa to be disabled, and when "Student" is selected, I want spdept to be disabled, but also this doesn't work. And based on that option will be chosen the next activity which will be opened after clicking the button.
Also, why doesn't it work to set the default date in my calendar? I tried multiple things found here, but none of them worked for me. My Android Studio doesn't show DatePicker, which I would prefer, only that Calendar.
public class SignInActivity extends Activity {
private Button bSignup;
private EditText etNume, etPrenume, etUsername, etPassword, etConfirmPass, etEmail;
private RadioButton rbMasc, rbFem;
private Spinner spTipUtilizator, spgrupa, spdept;
private ProgressBar progBar;
private Calendar calendar;
private int year, month, day, currentYear, defday, defmonth, defyear;
private List<String> tipUtilizatorList, grupaList;
private ArrayAdapter<String> spinnerArrayAdapterTipU;
private String nume,prenume,username,password,password2,email,masc,fem,sex,tipUser,dept,DataN;
private int grupa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
calendar=Calendar.getInstance();
calendar.set(1990,12,12);
bSignup = findViewById(R.id.buttonSignin);
etNume=findViewById(R.id.et_nume);
etPrenume=findViewById(R.id.et_prenume);
etUsername=findViewById(R.id.et_username);
etPassword=findViewById(R.id.et_password);
etConfirmPass = findViewById(R.id.et_confirmpassword);
etEmail=findViewById(R.id.et_email);
rbMasc=findViewById(R.id.radioButtonMasc);
rbFem=findViewById(R.id.radioButtonFem);
spTipUtilizator=findViewById(R.id.spinnerTipUtilizator);
spgrupa=findViewById(R.id.spinnerGrupa);
spdept=findViewById(R.id.spinnerDepartament);
progBar = findViewById(R.id.progressBar);
tipUtilizatorList=new ArrayList<>(Arrays.asList(getResources().getStringArray((R.array.tipUtilizator))));
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,tipUtilizatorList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTipUtilizator.setAdapter(adapter);
grupaList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.grupa)));
bSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nume = etNume.getText().toString().trim();
prenume = etPrenume.getText().toString().trim();
username = etUsername.getText().toString().trim();
password = etPassword.getText().toString().trim();
password2 = etConfirmPass.getText().toString().trim();
email = etEmail.getText().toString().trim();
masc = rbMasc.getText().toString().trim();
fem = rbFem.getText().toString().trim();
sex=fem;
tipUser = spTipUtilizator.getSelectedItem().toString().trim();
grupa = Integer.parseInt(spgrupa.getSelectedItem().toString().trim());
dept = spdept.getSelectedItem().toString().trim();
DataN = day+"/"+month+"/"+year;
progBar.setVisibility(View.VISIBLE);
if(rbFem.isChecked()) {
sex=fem;
}
else if(rbMasc.isChecked()) {
sex=masc;
}
spTipUtilizator.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Text = parent.getSelectedItem().toString();
if(Text.equals("Profesor")) {
spgrupa.getSelectedView().setEnabled(false);
spdept.getSelectedView().setEnabled(true);
Intent intent = new Intent(getApplicationContext(),StartProfesorActivity.class);
Profesor prof = new Profesor(nume,prenume,username,password,email,sex,dept,DataN);
intent.putExtra("profesor",prof);
startActivity(intent);
return;
}
else if(Text.equals("Student")) {
spgrupa.getSelectedView().setEnabled(true);
spdept.getSelectedView().setEnabled(false);
Intent intent = new Intent(getApplicationContext(),StartStudentActivity.class);
Student stud = new Student(nume,prenume,username,password,email,sex,grupa, DataN);
intent.putExtra("student",stud);
startActivity(intent);
return;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
}
}
Log:
D/AbsListView: in onLayout changed
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: MSG_WINDOW_FOCUS_CHANGED 1
V/InputMethodManager: Not IME target window, ignoring
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: MSG_RESIZED_REPORT: frame=Rect(266, 72 - 422, 1047) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl#27d7010[SignInActivity]: MSG_WINDOW_FOCUS_CHANGED 0
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: ViewPostIme pointer 0
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: ViewPostIme pointer 1
D/AbsListView: onTouchUp() mTouchMode : 0
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: Relayout returned: old=[266,72][422,1047] new=[266,72][422,1047] result=0x1 surface={valid=true 481098420224} changed=false
D/ViewRootImpl#27d7010[SignInActivity]: MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: MSG_WINDOW_FOCUS_CHANGED 0
I/zygote64: Compiler allocated 4MB to compile void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/OpenGLRenderer: prepareTree mLayerUpdateQueue is not empty, size = 1
name = PopupWindow$PopupBackgroundView, size (156, 975)
D/OpenGLRenderer: eglDestroySurface = 0x6ff4459d80
endAllActiveAnimators on 0x6ff591ec00 (DropDownListView) with handle 0x7003b6eb00
D/ViewRootImpl#cab402e[PopupWindow:ad4e773]: dispatchDetachedFromWindow
D/InputEventReceiver: channel '468478f PopupWindow:ad4e773 (client)' ~ Disposing input event receiver.
channel '468478f PopupWindow:ad4e773 (client)' ~NativeInputEventReceiver.
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 0
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 1
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 0
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 1
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 0
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 1
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 0
D/ViewRootImpl#27d7010[SignInActivity]: ViewPostIme pointer 1
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#54a19af nm : com.example.ancaa.proiectandroidquiz ic=com.android.internal.widget.EditableInputConnection#ba71bc
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
W/IInputConnectionWrapper: getCursorCapsMode on inactive InputConnection
W/IInputConnectionWrapper: getCursorCapsMode on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
D/OpenGLRenderer: eglDestroySurface = 0x7003ab7400
D/ViewRootImpl#27d7010[SignInActivity]: Relayout returned: old=[0,0][1080,1920] new=[0,0][1080,1920] result=0x5 surface={valid=false 0} changed=true
D/ViewRootImpl#27d7010[SignInActivity]: MSG_WINDOW_FOCUS_CHANGED 0
D/ViewRootImpl#27d7010[SignInActivity]: Relayout returned: old=[0,0][1080,1920] new=[0,0][1080,1920] result=0x1 surface={valid=false 0} changed=false
Application terminated.
You shouldn't create the OnItemSelectedListener inside the OnClickListener for your sign in button, instead you have to create it outside and save the selected option in a variable.
Then when the user clicks your sign in button, you check witch option was selected and start the correct Activity.
Looking at your code, you could simply save the intent to the next activity, and when the user clicks the button just start the Activity on that intent.
I've put a check for nullity before trying to start that intent, and you could show the user some dialog or Toast if no valid option was selected.
public class SignInActivity extends Activity {
private Button bSignup;
private EditText etNume, etPrenume, etUsername, etPassword, etConfirmPass, etEmail;
private RadioButton rbMasc, rbFem;
private Spinner spTipUtilizator, spgrupa, spdept;
private ProgressBar progBar;
private Calendar calendar;
private int year, month, day, currentYear, defday, defmonth, defyear;
private List<String> tipUtilizatorList, grupaList;
private ArrayAdapter<String> spinnerArrayAdapterTipU;
private String nume,prenume,username,password,password2,email,masc,fem,sex,tipUser,dept,DataN;
private int grupa;
private Intent activityToStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
calendar=Calendar.getInstance();
calendar.set(1990,12,12);
bSignup = findViewById(R.id.buttonSignin);
etNume=findViewById(R.id.et_nume);
etPrenume=findViewById(R.id.et_prenume);
etUsername=findViewById(R.id.et_username);
etPassword=findViewById(R.id.et_password);
etConfirmPass = findViewById(R.id.et_confirmpassword);
etEmail=findViewById(R.id.et_email);
rbMasc=findViewById(R.id.radioButtonMasc);
rbFem=findViewById(R.id.radioButtonFem);
spTipUtilizator=findViewById(R.id.spinnerTipUtilizator);
spgrupa=findViewById(R.id.spinnerGrupa);
spdept=findViewById(R.id.spinnerDepartament);
progBar = findViewById(R.id.progressBar);
tipUtilizatorList=new ArrayList<>(Arrays.asList(getResources().getStringArray((R.array.tipUtilizator))));
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,tipUtilizatorList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTipUtilizator.setAdapter(adapter);
grupaList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.grupa)));
bSignup.setOnClickListener(v -> {
nume = etNume.getText().toString().trim();
prenume = etPrenume.getText().toString().trim();
username = etUsername.getText().toString().trim();
password = etPassword.getText().toString().trim();
password2 = etConfirmPass.getText().toString().trim();
email = etEmail.getText().toString().trim();
masc = rbMasc.getText().toString().trim();
fem = rbFem.getText().toString().trim();
sex=fem;
tipUser = spTipUtilizator.getSelectedItem().toString().trim();
grupa = Integer.parseInt(spgrupa.getSelectedItem().toString().trim());
dept = spdept.getSelectedItem().toString().trim();
DataN = day+"/"+month+"/"+year;
progBar.setVisibility(View.VISIBLE);
if(rbFem.isChecked()) {
sex=fem;
}
else if(rbMasc.isChecked()) {
sex=masc;
}
if(activityToStart != null)
startActivity(activityToStart);
});
spTipUtilizator.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Text = parent.getSelectedItem().toString();
if(Text.equals("Profesor")) {
spgrupa.getSelectedView().setEnabled(false);
spdept.getSelectedView().setEnabled(true);
activityToStart = new Intent(getApplicationContext(),StartProfesorActivity.class);
Profesor prof = new Profesor(nume,prenume,username,password,email,sex,dept,DataN);
activityToStart.putExtra("profesor",prof);
return;
}
else if(Text.equals("Student")) {
spgrupa.getSelectedView().setEnabled(true);
spdept.getSelectedView().setEnabled(false);
activityToStart = new Intent(getApplicationContext(),StartStudentActivity.class);
Student stud = new Student(nume,prenume,username,password,email,sex,grupa, DataN);
activityToStart.putExtra("student",stud);
return;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Related
My app gets data from a PHP file. 3 normal textdata and 5 image urls. The app displays them in a recyclerview with cardviews.
My problem is, that the app crashes when getting empty image urls.
But with empty textdata the app works without problems.
Like:
textdata with content + image urls with content = works
Empty textdata + empty image urls = App crashes
Empty textdata + image urls with content = works
textdata with content + empty image urls = App crashes
This is the getting and sending (to RecyclerviewAdapter) Code:
public void JSON_DATA_WEB_CALL (String url){
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(solutionTemplate.this, GetDataAdapter1, exerciseAdapter);
recyclerView.setAdapter(recyclerViewadapter);
}
The mainproblem is:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Working:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
Not working:
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Getting image urls with content is necassary!
But it should work without it!
This is the GetDataAdapter:
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number1) {
this.phone_number = phone_number1;
}
public String getSubject2() {
return subject2;
}
public void setSubject2(String subject2) {
this.subject2 = subject2;
}
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageUrl2() {
return ImageURL2;
}
public void setImageUrl2(String imageServerUrl2) {
this.ImageURL2 = imageServerUrl2;
}
public String getImageUrl3() {
return ImageURL3;
}
public void setImageUrl3(String imageServerUrl3) {
this.ImageURL3 = imageServerUrl3;
}
public String getImageUrl4() {
return ImageURL4;
}
public void setImageUrl4(String imageServerUrl4) {
this.ImageURL4 = imageServerUrl4;
}
public String getImageUrl5() {
return ImageURL5;
}
public void setImageUrl5(String imageServerUrl5) {
this.ImageURL5 = imageServerUrl5;
}
RecyclerViewAdapter:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
final GetDataAdapter current = getItem(position - 1);
final ViewHolder holder1 = (ViewHolder) holder;
final ImageLoader imageLoader = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader2 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader3 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader4 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader5 = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(current.getImageUrl(),
ImageLoader.getImageListener(
holder1.imageView1,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader2.get(current.getImageUrl2(),
ImageLoader.getImageListener(
holder1.imageView2,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader3.get(current.getImageUrl3(),
ImageLoader.getImageListener(
holder1.imageView3,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader4.get(current.getImageUrl4(),
ImageLoader.getImageListener(
holder1.imageView4,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader5.get(current.getImageUrl5(),
ImageLoader.getImageListener(
holder1.imageView5,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
holder1.imageView1.setImageUrl(current.getImageUrl(), imageLoader);
holder1.imageView2.setImageUrl(current.getImageUrl2(), imageLoader2);
holder1.imageView3.setImageUrl(current.getImageUrl3(), imageLoader3);
holder1.imageView4.setImageUrl(current.getImageUrl4(), imageLoader4);
holder1.imageView5.setImageUrl(current.getImageUrl5(), imageLoader5);
holder1.NameTextView.setText(current.getName());
holder1.PhoneNumberTextView.setText(current.getPhone_number());
holder1.SubjectTextView.setText(current.getSubject2());
ImageAdapter:
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
PHP:
<?php
$conn = mysqli_connect('localhost', 'root', '','webapp');
$id = $_GET['id'];
$sql = "SELECT * FROM answers WHERE id='$id' ORDER BY id DESC";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array(
'url2'=>$row['images'],
'url3'=>$row['images2'],
'url4'=>$row['images3'],
'url5'=>$row['images4'],
'url6'=>$row['images5'],
'subject'=>$row['subject'],
'phone'=>$row['phone'],
'name'=>$row['name']));
}
echo json_encode(array_values($result));
mysqli_close($conn);
?>
If PHP sends url2, url3, url4... without content the app chrashes, but phone, name, subject with empty values works without problems.
I think Android has a Problem with converting empty imageurls and with displaying it.
EDIT:
A lot of users said that I have to add the Logcat:
07-16 13:12:10.713 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.solutionTemplate
07-16 13:12:10.822 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.Main2Activity
07-16 13:12:10.946 1578-2630/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:10.947 1578-2630/system_process D/EGL_emulation: eglCreateContext: 0x9c2be040: maj 2 min 0 rcv 2
07-16 13:12:10.953 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:10.962 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:11.323 1578-1592/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{e46f507 u0 com.example.jakob.webapplicationsave/.solutionTemplate t497 f}
07-16 13:12:11.372 1930-2076/com.android.launcher3 I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:11.374 1930-2076/com.android.launcher3 D/EGL_emulation: eglCreateContext: 0xae414660: maj 2 min 0 rcv 2
07-16 13:12:11.385 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:11.423 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:13.537 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38006369 , only wrote 37870012
07-16 13:12:14.795 13519-13519/com.example.jakob.webapplicationsave I/Process: Sending signal. PID: 13519 SIG: 9
07-16 13:12:14.814 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:14.815 1578-2630/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9b6834a0
07-16 13:12:14.830 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.830 1578-2182/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 13519 uid 10062
07-16 13:12:14.833 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.847 1578-1713/system_process D/GraphicsStats: Buffer count: 5
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-2182/system_process I/WindowState: WIN DEATH: Window{7af27b1 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity}
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-2182/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)'
07-16 13:12:14.848 1578-2179/system_process I/WindowState: WIN DEATH: Window{cd3daa3 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate}
07-16 13:12:14.848 1578-2179/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)'
07-16 13:12:14.853 1259-1259/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
07-16 13:12:14.853 1578-1963/system_process I/ActivityManager: Process com.example.jakob.webapplicationsave (pid 13519) has died
07-16 13:12:15.026 1578-1597/system_process W/AppOps: Finishing op nesting under-run: uid 1000 pkg android code 24 time=0 duration=0 nesting=0
07-16 13:12:17.958 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38145850 , only wrote 38008822
07-16 13:13:00.065 1259-1351/? D/hwcomposer: hw_composer sent 312 syncs in 60s
07-16 13:14:00.056 1259-1351/? D/hwcomposer: hw_composer sent 5 syncs in 60s
Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help
Hi I'm using FireStore to store data in remote database. However, I had a problem with using set and update method.
When I want to update some value in some documents and display dialog after update, my android app restarts. The below is logcat which is displayed when I proceed above process.
12-27 12:09:49.838 17014-17014/com.wecobell.www.doggy D/showUnlockDialog: OnSuccess
12-27 12:09:49.875 17014-17014/com.wecobell.www.doggy W/OpenGLRenderer: Points are too far apart 4.000001
12-27 12:09:49.908 17014-17014/com.wecobell.www.doggy D/MainActivity: onPause
12-27 12:09:49.930 17014-17014/com.wecobell.www.doggy D/MainActivity: ---- Network Status Check ----
12-27 12:09:49.932 17014-17014/com.wecobell.www.doggy D/MainActivity: Wifi Connection : true, 4G or 5G : false
12-27 12:09:49.943 17014-17014/com.wecobell.www.doggy D/MainActivity: onCreate
As you can see, MainActivity is reopened, when 'showUnlockDialog' is successfully displayed. How can I solve this problem?
/**
* 메소드명 : unlockProfile
* 설명 : Method that unlocks user's profile
*/
private void unlockProfile(final int position) {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
FireStore.unlockInterestedUser(firestore, currentUid, interestedUsers.get(position).getUid());
}
/**
* 메소드명 : showUnlockDialog
* 설명 : Method that displays dialog.
*/
private void showUnlockDialog(final int position) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.content("프로필을 보시려면 뼈다귀 포인트 5개가 필요합니다.")
.positiveText("적용")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
DocumentReference dc = FireStore.getPointOfUser(firestore, MyUser.getInstance().getUid());
FirebaseAuth fa = FirebaseAuth.getInstance();
FirebaseUser user = fa.getCurrentUser();
final DocumentReference me = FireStore.getUserInfo(firestore, user.getUid());
me.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Log.d("showUnlockDialog", "OnSuccess");
MyUser user = documentSnapshot.toObject(MyUser.class);
int newPoint = user.getPoint() - 5;
user.setPoint(newPoint);
me.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("showUnlockDialog", "unlockProfileMethod");
unlockProfile(position);
Toast.makeText(context, "업데이트 완료", Toast.LENGTH_SHORT).show();
}
});
}
});
}
})
.negativeText("취소")
.show();
}
So I am creating an app that requests permission to a users google account. I used mine to test and so I gave it permission and then removed it to see if it would ask for it again. It was still using the token it got so I deleted the app from my phone and reinstalled it. I didn't change any code and now all of a sudden it only shows the account page (to select which account) and then once I press ok, nothing shows to give it permission. In my run console I get the following:
$ adb push C:\Users\James Singleton\AndroidStudioProjects\ChffrAPI\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.jamessingleton.chffrapi
$ adb shell pm install -r "/data/local/tmp/com.example.jamessingleton.chffrapi"
pkg: /data/local/tmp/com.example.jamessingleton.chffrapi
Success
$ adb shell am start -n "com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25029 on device samsung-sm_g935v-0d75cc0d
E/Zygote: v2
W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0010
E/Zygote: accessInfo : 0
I/libpersona: KNOX_SDCARD checking this for 10269
I/libpersona: KNOX_SDCARD not a persona
W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.example.jamessingleton.chffrapi
I/art: Late-enabling -Xcheck:jni
D/ActivityThread: Added TimaKeyStore provider
D/RelationGraph: garbageCollect()
I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
D/ContextRelationManager: ContextRelationManager() : FEATURE_ENABLED=true
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/ResourcesManager: For user 0 new overlays fetched Null
I/InjectionManager: Inside getClassLibPath caller
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
W/art: Failed to open zip archive '/system/framework/dpmapi.jar': I/O Error
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
D/InjectionManager: InjectionManager
D/InjectionManager: fillFeatureStoreMap com.example.jamessingleton.chffrapi
I/InjectionManager: Constructor com.example.jamessingleton.chffrapi, Feature store :{}
I/InjectionManager: featureStore :{}
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.google.android.gms
I/InjectionManager: Inside getClassLibPath caller
D/ResourcesManager: For user 0 new overlays fetched Null
D/ChimeraCfgMgr: Reading stored module config
W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000007/n/arm64-v8a
D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
D/ChimeraFileApk: Classloading successful. Optimized code found.
D/Activity: performCreate Call Injection manager
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.WifivsDataDialog isFragment :true
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{3c6164c V.E...... R.....I. 0,0-0,0}
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/SecWifiDisplayUtil: Metadata value : SecSettings2
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.MainActivity isFragment :false
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{ead695 I.E...... R.....ID 0,0-0,0}
I/Adreno: QUALCOMM build : c0299d7, I241dab1ec4
Build Date : 01/25/16
OpenGL ES Shader Compiler Version: XE031.06.00.05
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.HB.1.1.1.06.00.01.063.117
Remote Branch : NONE
Reconstruct Branch : NOTHING
D/libEGL: eglInitialize EGLDisplay = 0x7f62194188
I/OpenGLRenderer: Initialized EGL, version 1.4
I/InjectionManager: dispatchCreateOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
I/InjectionManager: dispatchPrepareOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : com.example.jamessingleton.chffrapi
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2598350
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/WifiManager: isAllowWifiWarning() -> isCscWifiEnableWarning : false ChinaNalSecurityType :
D/ViewRootImpl: #3 mView = null
E/ViewRootImpl: sendUserActionEvent() mView == null
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 1128) vi=Rect(0, 96 - 0, 1128) or=1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/Timeline: Timeline: Activity_launch_request id:android time:2603031
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : true
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2605454
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : false
Application terminated.
Nothing changed in my code so I have no idea why I am not getting the pop up to allow me to give the app permission.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this;
private AccountManager mAccountManager;
private AuthPreferences authPreferences;
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "";
static final String API_URL = "https://api.comma.ai/v1/auth/?access_token=";
static final String ClientId = "45471411055-m902j8c6jo4v6mndd2jiuqkanjsvcv6j.apps.googleusercontent.com";
static final String ClientSecret = "";
static final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
mAccountManager = AccountManager.get(this);
authPreferences = new AuthPreferences(this);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
doCoolAuthenticatedStuff();
new RetrieveFeedTask().execute();
} else {
chooseAccount();
}
}
});
// Button queryButton = (Button) findViewById(R.id.queryButton);
//
// queryButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (isNetworkAvailable() == true) {
// new RetrieveFeedTask().execute();
// Intent intent = new Intent(context, NavDrawerActivity.class);
// startActivity(intent);
// } else {
// Toast.makeText(MainActivity.this, "No Network Service, please check your WiFi or Mobile Data Connection", Toast.LENGTH_SHORT).show();
// }
// }
// });
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "WiFi");
myDiag.setCancelable(false);
}
}
private void doCoolAuthenticatedStuff() {
Log.e("AuthApp", authPreferences.getToken());
}
private void chooseAccount() {
Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
public void requestToken() {
Account userAccount = null;
String user = authPreferences.getUser();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
for (Account account : mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(user)) {
userAccount = account;
break;
}
}
mAccountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, new OnTokenAcquired(), null);
}
private void invalidateToken() {
AccountManager mAccountManager = AccountManager.get(this);
mAccountManager.invalidateAuthToken("com.google", authPreferences.getToken());
authPreferences.setToken(null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == AUTHORIZATION_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
authPreferences.setUser(accountName);
// invalidate old tokens which might be cached. we want a fresh
// one, which is guaranteed to work
invalidateToken();
requestToken();
}
}
}
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
Bundle bundle = result.getResult();
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, AUTHORIZATION_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
authPreferences.setToken(token);
System.out.println(authPreferences);
doCoolAuthenticatedStuff();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "Available");
return true;
}
Log.e("Network Testing", "Not Available");
return false;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL(API_URL + authPreferences.getToken());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = urlConnection.getResponseCode();
System.out.println("GET Response code:" + responseCode);
// urlConnection.addRequestProperty("client_id", ClientId);
// urlConnection.addRequestProperty("client_secret", ClientSecret);
// urlConnection.setRequestProperty("Authorization", "JWT " + authPreferences);
Log.i("URL", url.toString());
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
//
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}}
And then here is my AuthPreferences.java
public class AuthPreferences {
private static final String KEY_USER = "user";
private static final String KEY_TOKEN = "token";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context
.getSharedPreferences("auth", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.commit();
}
public void setToken(String password) {
Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, null);
}
public String getToken() {
return preferences.getString(KEY_TOKEN, null);
}
}
myOnClickListener = new MyOnClickListener(this);
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
static class MyOnClickListener implements View.OnClickListener{
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = (String) textViewName.getText();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}
This has worked before, but isnt working now. Did I do anything wrong? I have 2 RecyclerViews but they are not visible together. This click listener is for one RecyclerView only.
LogCat
01-31 18:41:17.514 3441-3441/com.wc.gap.worldcupfixture I/art﹕ Late-enabling -Xcheck:jni
01-31 18:41:17.761 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:41:17.767 3441-3441/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:41:17.792 3441-3471/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:41:17.793 3441-3471/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:41:17.805 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
01-31 18:41:57.529 3441-3470/com.wc.gap.worldcupfixture I/System.out﹕ 544, 543, 646, 797, 64, 66, 987
01-31 18:43:25.218 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:43:25.224 4242-4242/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:43:25.257 4242-4271/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:43:25.258 4242-4271/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:43:25.270 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
When implementing View.OnClickListener, do it like below.
public class YourClass extends Activity implements View.OnClickListener
#Override
protected void onCreate(Bundle savedInstanceState) {
//Component setup here.
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
nRecyclerView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = textViewName.getText().toString();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}