If i have 10 EditText and the user enter only in 5 then i exit my app on click the onBackPressed Button without submit the EditText data which is entering , and then when i restart my app i want to same activity on start up.Thanks to appriceat.
public class Registration_Form extends Activity {
EditText et_CompanyName;
EditText et_EmployeeName;
EditText et_CompanyWebsite;
EditText et_ContactNumber;
EditText et_Email_Id;
Button btnSubmit;
DatabaseHelper databaseHelper;
SQLiteDatabase db;
RadioGroup radioGroup_FinancialYaer;
RadioButton radioButton_FinancialYaer;
String strFinancialYear;
String appWidgetId = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_details);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor edit = prefs.edit();
boolean alldataSaved=prefs.getBoolean("SecondRun",false);
et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);
et_CompanyName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Name"+appWidgetId,et_CompanyName.getText().toString());
edit.commit();
}
}
});
et_EmployeeName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Employee_Name"+appWidgetId,et_EmployeeName.getText().toString());
edit.commit();
}
}
});
et_CompanyWebsite.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Website"+appWidgetId,et_CompanyWebsite.getText().toString());
edit.commit();
}
}
});
et_ContactNumber.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Contact_Number"+appWidgetId,et_ContactNumber.getText().toString());
edit.commit();
}
}
});
et_Email_Id.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Email_Id"+appWidgetId,et_Email_Id.getText().toString());
edit.commit();
}
}
});
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved == false)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("SecondRun",true);
editor.commit();
Log.e("Second"," Steps !!!!");
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);
btnSubmit = (Button) findViewById(R.id.buttonSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String stringEmail_Id = et_Email_Id.getText().toString()
.trim();
final String stringCompanyWebsite = et_CompanyWebsite.getText()
.toString().trim();
if ((et_CompanyName.getText().toString().isEmpty()))
{
et_CompanyName.setError("Field Can Not Be Empty !");
}
else if (!et_CompanyName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_CompanyName.setError("Accept Alphabets Only.");
}
else if ((et_EmployeeName.getText().toString().isEmpty()))
{
et_EmployeeName.setError("Field Can Not Be Empty !");
}
else if (!et_EmployeeName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_EmployeeName.setError("Accept Alphabets Only.");
}
else if ((et_CompanyWebsite.getText().toString().isEmpty()))
{
et_CompanyWebsite.setError("Field Can Not Be Empty !");
}
else if (!isValidUrl(stringCompanyWebsite))
{
et_CompanyWebsite.setError("Invalid URL");
}
else if ((et_ContactNumber.getText().toString().isEmpty()))
{
et_ContactNumber.setError("Field Can Not Be Empty !");
}
else if (!isValidEmail(stringEmail_Id))
{
et_Email_Id.setError("Invalid Email");
}
else
{
String stringCompanyName = et_CompanyName.getText()
.toString().trim();
String stringContactNumber = et_ContactNumber.getText()
.toString().trim();
String stringEmployeeName = et_EmployeeName.getText()
.toString().trim();
int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
Log.e("selectedId "," = " + selectedId);
radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
Log.e("strRadioButton "," = " + strFinancialYear);
databaseHelper.insertRegstrationDetails(stringCompanyName,
stringEmployeeName, stringCompanyWebsite,
stringContactNumber, stringEmail_Id, strFinancialYear);
System.out.println("Data Inserted Successfully !!! ");
Intent iSubmit = new Intent(Registration_Form.this,Staff_Employee_Details.class);
startActivity(iSubmit);
finish();
}
}
});
}
you can simply use this
Intent intent = getIntent();
finish();
startActivity(intent);
I hope thats work
You can use sharedPreference for this. you can save the value of each edittext in one sharedprefrerece (with unique key for each edittext and set values at the time of focus change. see example:)
EditText txtEdit= (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
//do job here when Edittext lose focus
//means save value here
}
});
and load these saved value at on create.
Hope you are getting some idea from this
Edit: This is for your condition
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved==false)
{
//stay in this activiy
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
That's not how Android works. You cannot "restore" the same Activity in that fashion. What you CAN however do is save out the EditText content, for example in the onPause() or onStop() function, save out the contents of the EditTexts as Strings, put them in a List, then serialize that List out into a file. In the onResume() or onStart() method, deserialize this data from the file.
An example for such serialization is shown here, but I'll also paste it here:
Put objects into bundle
Serialization:
private List<String> list = new ArrayList<String>();
#Override
public void onPause()
{
super.onPause();
FileOutputStream out = null;
try
{
out = openFileOutput("ModelBackup",Context.MODE_PRIVATE);
try
{
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(list);
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
catch(FileNotFoundException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(out != null) out.close();
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
}
Deserialization:
#Override
public void onResume()
{
super.onResume();
FileInputStream in = null;
try
{
in = openFileInput("ModelBackup");
ObjectInputStream oos = new ObjectInputStream(in);
try
{
list = (List<String>)oos.readObject();
}
catch(ClassNotFoundException e)
{
list = null;
}
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(in != null) in.close();
}
catch(IOException e) {}
}
}
If restarting an activity from a fragment, I would do it like so:
new Handler().post(new Runnable() {
#Override
public void run()
{
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().overridePendingTransition(0, 0);
getActivity().finish();
getActivity().overridePendingTransition(0, 0);
startActivity(intent);
}
});
Related
Ive got a problem. Theres a String languages and I have MainActivity(A) and ChooseLanguageActivity(B). From A user goes to B to choose language after that he intented to A and languages get value from intent. I need to set default value for this variable languages. I tried to use it in onCreate. But I don't need use default value each time activity created. I need to use it only when app launching after that this variable need to use the value which it get from activity B intent.
Thats code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
SharedPreferences sPref;
final String SAVED_TEXT = "saved_text";
final String TAG = "myTag";
String language;
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
language = "en";
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveText();
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
loadText();
}
#Override
protected void onDestroy() {
super.onDestroy();
sPref = null;
}
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
translatedTextInput.setText(savedText);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}
public void sendJsonRequest() {
Intent myIntent = getIntent();
language = myIntent.getStringExtra("short");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}
P.S.Hmmm i don't understand that -1. If you make -1 at least write in comment whats wrong with question not to duplicate this mistakes next time.
Short answer: Save boolean activityWasLauched on SharedPreferences
When the app launches always put the variable as false. Inside of the onCreate of the Activity put it true, then you can use:
if (activityWasLauched == false){
//use the default
}
else{
//use a bundle and get the value from an intent
}
To simplify the much as possible the use of SharedPreferences:
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
if(score > high_score)
{
editor.putInt("high_score", score);
editor.apply(); /* Edit the value here*/
}
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String high_score= sp.getInt("high_score", "");
Remember that variables are stored in memory and are destroyed whenever your app stops running. To store a value more permanently, you need to save it to disk. For simple values, SharedPreferences is the way to go. You should load the value of languages from SharedPreferences when your app starts. If no such value exists, save a default value so that the next time your app starts, it just reads the value. If something in the app changes the value of this variable, such as a user action, be sure to save the new value so that it is correct the next time your app starts.
Hope I understood you right..
First:
Launch your "ChooseLanguageList" activity using startActivityForResult()
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivityForResult(intent, ANY_REQUEST_CODE);
Second:
In your "ChooseLanguageList" after setting your language return result to "MainActivity" using set result
Intent returnIntent = new Intent();
returnIntent.putExtra(MY_LANG_EXTRA, language);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Third:
Back to "MainActivity".. catch the returned result using onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ANY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
language = data.getStringExtra(MY_LANG_EXTRA);
/* Save language in Shared Preferences */
}
Fourth:
Save your retrieved language in a Shared preference
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(/*Key:*/"my_lang", /*value:*/language);
editor.apply();
Fifth:
Now every time you want to use language (eg. in onCreate()), just retrieve it from Shared Preferences, stating a default value in case it wasn't found
String language = sp.getString(/*Key:*/"my_lang", "en/*Default value*/");
Now each time "MainActivity" launches it will try to get language from Shared Prefs with key "my_lang", but if there is nothing there it will fall back to the default "en" until a new value is retrieved from "ChooseLanguageList" activity.
Hope this answers your question
I twice get anr when i swipe the app from recent activities. And then the app works fine also I get an anr when I switch to landscape mode. The app works as expected as long as it is not oriented landscape or swiped from recent apps.
Can someone point out what I am doing wrong here.
Thanks
MyService.java:
public class MyService extends Service {
public static boolean started = false;
public static String TRANSACTION_DONE = "com.example.root.project";
private WebSocketClient client = null;
public static SQLiteDatabase myDataBase = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if(started){
String message = intent.getStringExtra("message");
if(client != null){
client.send(message);
}
}
if (!started) {
myDataBase = openOrCreateDatabase("Messages.db", MODE_PRIVATE, null);
myDataBase.execSQL("CREATE TABLE IF NOT EXISTS messages " +
"(tag TEXT primary key, message TEXT);");
started = true;
URI uri = null;
try {
uri = new URI(intent.getStringExtra("ip"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
client = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.accumulate("addme",intent.getStringExtra("name"));
} catch (JSONException e) {
e.printStackTrace();
}
client.send(jsonObject.toString());
}
#Override
public void onMessage(String message) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonObject.has("resolve")) {
PendingIntent notificIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), 0);
// Builds a notification
NotificationCompat.Builder mBuilder =
null;
try {
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.add)
.setContentTitle(jsonObject.getString("name"))
.setTicker(jsonObject.getString("resolve"))
.setContentText(jsonObject.getString("destination"));
} catch (JSONException e) {
e.printStackTrace();
}
// Defines the Intent to fire when the notification is clicked
mBuilder.setContentIntent(notificIntent);
// Set the default notification option
// DEFAULT_SOUND : Make sound
// DEFAULT_VIBRATE : Vibrate
// DEFAULT_LIGHTS : Use the default light notification
mBuilder.setDefaults(Notification.DEFAULT_ALL);
// Auto cancels the notification when clicked on in the task bar
mBuilder.setAutoCancel(true);
// Gets a NotificationManager which is used to notify the user of the background event
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Post the notification
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
} else if (jsonObject.has("remove")) {
try {
String tag = jsonObject.getString("remove");
myDataBase.execSQL("DELETE FROM messages WHERE tag = " + tag + ";");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
} else {
try {
myDataBase.execSQL("INSERT INTO messages (tag, message) VALUES ('" +
jsonObject.getString("tag") + "', '" + message + "');");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
}
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d("myTag", "onClose: websocket closing ");
Toast.makeText(getApplicationContext(),"closing websocket",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
client.connect();
}
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Toast.makeText(getApplicationContext(),"closing client",Toast.LENGTH_LONG).show();
client.close();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("myTag", "onDestroy: service being destroyed ");
try {
client.closeBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(this,"Service is closing on destroy called",Toast.LENGTH_LONG).show();
}
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private String name;
private String ip;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogTitle);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogDesc);
String title = editText.getText().toString().trim();
String desc = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("title", title);
jsonObject.accumulate("desc", desc);
jsonObject.accumulate("name",name);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(MyPreferences.isFirst(this)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.login_dialog, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogName);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogIp);
name = editText.getText().toString().trim();
ip = editText2.getText().toString().trim();
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("name", name);
intent.putExtra("ip", ip);
MainActivity.this.getSharedPreferences("my_preferences",MODE_PRIVATE).edit().putString("name",name).putString("ip",ip).commit();
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(MainActivity.this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}else {
Intent intent = new Intent(this, MyService.class);
name = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("name","no_name");
ip = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("ip","no_ip");
intent.putExtra("name",name);
intent.putExtra("ip",ip);
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
}
#Override
protected void onDestroy() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
if(jsonObject.has("remove")){
adapter.remove(jsonObject.getString("remove"));
adapter.update();
}else {
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
adapter.update();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<ListViewData> objects;
public void add(String title, String desc, String tag) {
objects.add(new ListViewData(title, desc, tag));
}
public void remove(String tag){
for(ListViewData data : objects){
if(data.getTag().equals(tag)){
objects.remove(data);
break;
}
}
}
public void update(){
notifyDataSetChanged();
}
private class ViewHolder {
TextView title;
TextView description;
Button resolve;
Button subscribe;
Button unSubscribe;
}
public CustomAdapter(Context context) {
inflater = LayoutInflater.from(context);
objects = new ArrayList<>();
}
public int getCount() {
return objects.size();
}
public ListViewData getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_list_layout, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.description = (TextView) convertView.findViewById(R.id.desc);
holder.resolve = (Button) convertView.findViewById(R.id.resolve);
holder.subscribe = (Button) convertView.findViewById(R.id.subscribe);
holder.unSubscribe = (Button) convertView.findViewById(R.id.unsubscribe);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(objects.get(position).getTitle());
holder.description.setText(objects.get(position).getDescription());
holder.resolve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.name);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.destination);
String name = editText.getText().toString().trim();
String destination = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("name", name);
jsonObject.accumulate("destination", destination);
jsonObject.accumulate("resolve",objects.get(position).getTag());
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
holder.subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("subscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
holder.unSubscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("unsubscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return convertView;
}
}
}
class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
I tried to send data from my app to my Arduino board to make the led light.
The problem is that if I send from my main activity it works but if I send it from a second activity (HolopickerColor), it doesn't work and I don't get any errors.
Thanks for your anwsers.
MainActivity :
public class MainActivity extends AppCompatActivity{
private Button mPairedBtn;
Button on, find;
public BluetoothAdapter BA;
private ProgressDialog mProgressDlg;
// public ConnectedThread mConnectedThread;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private DrawerLayout mDrawerLayout;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button btnOn, btnOff;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.btn_enable);
find = (Button) findViewById(R.id.btn_scan);
mPairedBtn = (Button) findViewById(R.id.btn_view_paired);
BA = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
switch (menuItem.getItemId()) {
case R.id.nav_item_colorlight:
Intent color = new Intent(MainActivity.this, HolopickerColor.class);
// color.putExtra("color", ConnectedThread.getInstance());
startActivity(color);
break;
case R.id.nav_item_effectlight:
Intent light = new Intent(MainActivity.this, LightEffect.class);
startActivity(light);
break;
case R.id.nav_item_music:
Intent music = new Intent(MainActivity.this, Music.class);
startActivity(music);
break;
case R.id.nav_item_about:
Intent about = new Intent(MainActivity.this, About.class);
startActivity(about);
break;
}
return true;
}
});
mProgressDlg.setMessage("Scanning...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
BA.cancelDiscovery();
}
});
if (BA == null) {
showUnsupported();
} else {
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = BA.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BA.startDiscovery();
}
});
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BA.isEnabled()) {
BA.disable();
showDisabled();
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (BA.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/* r = 255;
g = 15;
b = 50;
mConnectedThread.write("r"+Integer.toString(r)+"\n"); // Send "0" via Bluetooth
mConnectedThread.write("g"+Integer.toString(g)+"\n");
mConnectedThread.write("b"+Integer.toString(b)+"\n");*/
ConnectedThread.getInstance().write("1");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//cathode nen 1 la off, o la on
ConnectedThread.getInstance().write("0"); // Send "1" via Bluetooth //gui nhan ne
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
//Get MAC address from DeviceListActivity via intent
// Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
//address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// MAC-address of Bluetooth module (you must edit this line)
address = "30:14:10:09:07:86";
//create device and set the MAC address
BluetoothDevice device = BA.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
ConnectedThread.createInstance(btSocket);
ConnectedThread.getInstance().start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onPause() {
if (BA != null) {
if (BA.isDiscovering()) {
BA.cancelDiscovery();
}
}
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
Toast.makeText(getApplicationContext(), "on", Toast.LENGTH_LONG).show();
on.setText("Disable");
on.setEnabled(true);
mPairedBtn.setEnabled(true);
find.setEnabled(true);
}
private void showDisabled() {
Toast.makeText(getApplicationContext(), "off", Toast.LENGTH_LONG).show();
on.setText("Enable");
on.setEnabled(true);
mPairedBtn.setEnabled(false);
find.setEnabled(false);
}
private void showUnsupported() {
Toast.makeText(getApplicationContext(), "Bluetooth is unsupported by this device", Toast.LENGTH_LONG).show();
on.setText("Enable");
on.setEnabled(false);
mPairedBtn.setEnabled(false);
find.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
Second activity :
public class HolopickerColor extends AppCompatActivity implements ColorPicker.OnColorChangedListener {
private TextView text;
com.larswerkman.holocolorpicker.ColorPicker picker;
SVBar svBar ;
Button test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holopicker_color);
picker = (ColorPicker) findViewById(R.id.picker);
svBar = (SVBar) findViewById(R.id.svbar);
text = (TextView) findViewById(R.id.color1);
picker.addSVBar(svBar);
picker.getColor();
picker.setOnColorChangedListener(this);
picker.setShowOldCenterColor(false);// Tat mau cu
test = (Button)findViewById(R.id.test);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConnectedThread.getInstance().write("r255\n");
Toast.makeText(getBaseContext(),"yes",Toast.LENGTH_LONG).show();
}
});
//ConnectedThread.getInstance().start();
}
public void onColorChanged(int color) {
// TODO Auto-generated method stub
text.setTextColor(color);//hien mau len chu
if (ConnectedThread.getInstance() != null) {
int r = (color >> 16) & 0xFF;//xuat kieu mau ra thanh chu
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
// mTcpClient.sendMessage(Integer.toHexString(picker.getColor()));
ConnectedThread.getInstance().write("r255");//gui ko nhan ne
Here is the ConnectedThread :
class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final OutputStream mmOutStream; // cai nay e can implement Serializable nua
private static ConnectedThread instance = null;
private ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
}
public static void createInstance(BluetoothSocket socket) {
if (instance == null) {
instance = new ConnectedThread(socket);
}
}
public static ConnectedThread getInstance() {
return instance;
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
cancel();
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
The problem is that you are creating your ConnectedThread singleton instance using a BluetoothSocket, and then you close that same socket in the onPause method of your activity. So basically, after onPause has been called, the ConnectedThread instance cannot send anything anymore. Instead of this you should have ConnectedThread manage the socket, i.e. keep a reference to it and then close it when you no longer need it or have detected a problem.
By the way, each time you call write on ConnectedThread after the socket is closed, your cancel method is called. You would have been able to easily detect the problem if you were not silencing exceptions in this method. This is why you should never have an empty catch block.
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
I need to check the following information on my application, if the text equals "Alpha" then it starts a new activity, else it will go on the usual code. Actually the usual code from "sendPack" work fine without the 'if' rule.
I just run into this problem and don't know how to proceed from here.
its probably a stupid mistake, sorry for this.
how to fix it?
public void Send(View view) throws IOException {
BdLocal bd = new BdLocal(this);
String text = bd.getEmpId();
if (text.equals("Alpha")) {
Intent intent = new Intent(BetaActivity.this, AlphaSetup.class);
startActivityForResult(intent, 0);
} else {
new transmitirInspecao().execute();
}
}
public class sendPack extends AsyncTask<String, Void, String> {
ProgressDialog pdialog;
int boxSelected = 0;
#Override
protected String doInBackground(String... params) {
BdLocal bd = new BdLocal(getApplicationContext());
BdCloud bdc = new BdCloud();
String ret = null;
for (CheckBox aCheckBoxArrayList : checkBoxArrayList) {
if (aCheckBoxArrayList.isChecked()) {
boxSelected++;
try {
int id = (Integer) aCheckBoxArrayList.getTag();
Pack pack = bd.readPackID(id);
ret = bdc.sendPack(pack, params[0], bd.getDspHash());
ret = ret.trim();
if (ret.equals("sucess".trim())) {
bd.MarkAsSend(id);
}
} catch (IOException e) {
//e.printStackTrace();
}
}
}
if (boxSelected <= 0) {
return "none";
}
return ret;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(BetaActivity.this);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setMessage(getResources().getString(R.string.send));
pdialog.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdialog.dismiss();
String msg = "Null";
if (result.equals("success")) {
msg = getResources().getString(R.string.success_send);
} else if (result.equals("img")) {
msg = getResources().getString(R.string.error_ftp);
} else if (result.equals("oper")) {
msg = getResources().getString(R.string.error_operation);
} else if (result.equals("none")) {
msg = getResources().getString(R.string.non_selected);
} else {
msg = getResources().getString(R.string.error_send);
}
AlertDialog alert;
AlertDialog.Builder builder = new AlertDialog.Builder(BetaActivity.this);
builder.setMessage(msg);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
alert = builder.create();
alert.show();
final Dialog login = new Dialog(this); //here is the message "Dialog cannot be applied" to Send, what should i do?
login.setContentView(R.layout.ins_dialog);
login.setTitle(R.string.insira_dados_op);
Button btnLogin = (Button) login.findViewById(R.id.btnLogin);
Button btnCancel = (Button) login.findViewById(R.id.btnCancel);
final EditText txtUsername = (EditText) login.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) login.findViewById(R.id.txtPassword);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtUsername.getText().toString().trim().length() > 0) {
if (txtPassword.getText().toString().trim().length() > 0) {
BdCloud bdc = new BdCloud();
BdLocal bdl = new BdLocal(BetaActivity.this);
String[] ret = bdc.loginOp(txtUsername.getText().toString().trim(), txtPassword.getText().toString().trim(), bdl.getDspHash());
if (ret[0].equals("true")) {
new Send().execute(ret[1]);
login.dismiss();
} else {
Toast.makeText(betaActivity.this, getResources().getString(R.string.error_inval), Toast.LENGTH_LONG).show();
}
} else {
txtPassword.setError(getResources().getString(R.string.error_field_required));
txtPassword.requestFocus();
}
} else {
txtUsername.setError(getResources().getString(R.string.error_field_required));
txtUsername.requestFocus();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login.dismiss();
}
});
login.show();
}
}