error : constant expression required - java

I want to open a new activity when I click on one of the name of the "string", for example, click on "pila 12v" and open new activity, in this case open "Main5Activity".
When placing the "case values [0]" a message appears:constant expression required.
package com.example.epson.mp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
AutoCompleteTextView values;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] values = new String[]{"bateria 9v", "pila 9v", "bateria 12v", "pila 12v"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,values);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtMercancias);
textView.setThreshold(3);//will start working from third character
textView.setAdapter(adapter); //setting the adapter data into the AutoCompleteTextView
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LinearLayout ll = (LinearLayout) view;
//This will give you the string value of selected list item
TextView listItem = (TextView) ll.getChildAt(0);
//You can do this or apply own logic to find the selected value case
switch (listItem.getText().toString()){
case values[0]:
Intent myintent0 = new Intent(view.getContext(), Main2Activity.class);
startActivityForResult(myintent0, 0);
break;
case values[1]:
Intent myintent1 = new Intent(view.getContext(), Main3Activity.class);
startActivityForResult(myintent1, 1);
break;
case values[2]:
Intent myintent2 = new Intent(view.getContext(), Main4Activity.class);
startActivityForResult(myintent2, 2);
break;
case values[3]:
Intent myintent3 = new Intent(view.getContext(), Main5Activity.class);
startActivityForResult(myintent3, 3);
break;
}
}
});
}
}

Related

Pass array list to fragment?

My problem is, that i am trying to pass
final List<PieEntry> entries = new ArrayList<>(); to another fragment, which is more or less empty until now.
My complete code is this: ( of the fragment which initiates the ArrayList)
package com.example.nextpietwo;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tvLabel2 = (TextView) view.findViewById(R.id.textView2);
//Alle Objekte hier einfügen (wie textview tvavel2)
final List<PieEntry> entries = new ArrayList<>();
final Button button = (Button) view.findViewById(R.id.button);
final TextView textView = (TextView) view.findViewById(R.id.textView);
final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
final EditText editText = (EditText) view.findViewById(R.id.editText);
final EditText editText2 = (EditText) view.findViewById(R.id.editText2);
final EditText editText3 = (EditText) view.findViewById(R.id.editText3);
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
if (editText3.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
} else if (editText2.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
} else {
String nomen = (editText3.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
entries.add(new PieEntry(number, nomen));
Bundle args = new Bundle();
args.putStringArrayList("array", ArrayList);
FirstFragment.setArguments(args);
editText3.setText("");
editText2.setText("");
editText3.requestFocus();
}
}
});
return view;
}
}
Simple explanations are appreciated!
Thanks in advance.
First of all make the make you PieEntry Parcelable by implementing interface Parcelable
Code to writeen in first Fragemnt
SecondFragment secondfragment //where data needs to be pass
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", data);
secondfragment.setArguments(bundle);
data is a list of PieEntry
Code to written in second Fragemnt
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
data =getArguments().getParcelableArrayList("data");
}
}

wrong 2nd Argument Type

I am implementing navigation drawer in my app and having a code as below
MainActivity.java
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.project.project.TimeSheet.ObjectDrawerItem;
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// 2.1 create ActionBarDrawerToggle
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.mipmap.timesheet, "Time Sheet");
drawerItem[1] = new ObjectDrawerItem(R.mipmap.claims, "Claims");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment = new Claims();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
I'm seeing a red line underneath fragment
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
When I point to the fragment , I get
Wrong 2nd ArgumentType.Found 'android.support.v4.app.Fragment', required 'android.app.Fragment';
And this is part of my Information activity
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import com.example.project.project.database.MyDatabaseHelper;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Information extends Fragment implements View.OnClickListener {
private Spinner spinner;
private MyDatabaseHelper dbHelper;
private com.example.project.project.API.InfoAPI ts;
private static EditText txtDate;
private DateDialog dialog;
private static String a;
private static String date1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View info = inflater.inflate(R.layout.information, container, false);
dialog=new DateDialog();
ts = new com.example.project.project.API.InfoAPI(getActivity());
txtDate = (EditText) info.findViewById(R.id.editText5);
spinner = (Spinner) info.findViewById(R.id.spinner);
txtDate.setOnClickListener(this);
addItemsOnSpinner();
btnSaved.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String date=txtDate.getText().toString();
ts.insertTimeSheet(spinner.getSelectedItem().toString(),spinner2.getSelectedItem().toString(),date,spinner3.getSelectedItem().toString());
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
Button button=(Button)info.findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), WorkForce.class);
a = spinner.getSelectedItem().toString();
intent.putExtra("a",a);
startActivity(intent);
}
});
return info;
}
public void onClick(View arg0) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialog.show(ft, "DatePicker");
}
public void addItemsOnSpinner() {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
LogCat error
Error:(86, 80) error: incompatible types: android.support.v4.app.Fragment cannot be converted to android.app.Fragment
If I import android.app.Fragment to both activities, I get incompatible types in my Information.java
public void onClick(View arg0) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialog.show(ft, "DatePicker");
}
Change
getFragmentManager()
to
getSupportFragmentManager()

Android Studio always opens same incorrect page

I cannot figure this out. My app will always go to the .Weather class no matter what I click on.
package com.example.matmap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class ResourcesPage extends Activity implements OnClickListener {
LinearLayout display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resources_page);
//display = (LinearLayout) findViewById(R.id.menuSweet);
LinearLayout locate = (LinearLayout) findViewById(R.id.locate);
LinearLayout ndsu = (LinearLayout) findViewById(R.id.ndsu);
LinearLayout weather = (LinearLayout) findViewById(R.id.weather);
LinearLayout contact = (LinearLayout) findViewById(R.id.contact);
locate.setOnClickListener(this);
ndsu.setOnClickListener(this);
weather.setOnClickListener(this);
contact.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
case R.id.weather:
Intent myIntent3 = new Intent(getApplicationContext(), Weather.class);
startActivity(myIntent3);
break; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resources_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menuHome){
Intent i = new Intent(getApplicationContext(), ResourcesPage.class);
startActivity(i);
}
return true;
}
}
Trying to get to the mapview class
package com.example.matmap;
import android.app.Activity;
import android.os.Bundle;
public class MapView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapview);
}
}
I don't know what the problem is since I've done these same things before and it's worked perfectly...
You should add break in each case statement
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
break;
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
break;
You're missing breaks:
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
break;
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
break;
case R.id.weather:
Intent myIntent3 = new Intent(getApplicationContext(), Weather.class);
startActivity(myIntent3);
break;
}
}

How Do I Get Extra From an Intent (as a type Long)?

I have this problem accessing an extra from an intent.
The value i'm parsing is a long type, and I need this value to be stored in a database.
So this is what I have so far:
MainActivity:
package com.example.calendar;
import java.sql.Date;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CalendarView;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity implements OnClickListener {
private AppointmentsData appointments;
CalendarView calendar;
Date date = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View createButton = findViewById(R.id.btn_create);
View editButton = findViewById(R.id.btn_viewEdit);
View deleteButton = findViewById(R.id.btn_delete);
View moveButton = findViewById(R.id.btn_move);
View searchButton = findViewById(R.id.btn_search);
View translateButton = findViewById(R.id.btn_translate);
View exitButton = findViewById(R.id.exit);
createButton.setOnClickListener(this);
editButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
moveButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
translateButton.setOnClickListener(this);
exitButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
date = new Date(year, month, dayOfMonth);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.btn_create:
i = new Intent(this, CreateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_viewEdit:
i = new Intent(this, EditViewAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_move:
i = new Intent(this, MoveAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_delete:
i = new Intent(this, DeleteAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_search:
i = new Intent(this, SearchAppointment.class);
startActivity(i);
break;
case R.id.btn_translate:
i = new Intent(this, TranslateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.exit:
finish();
break;
}
}
}
And the other Activity to use the value:
package com.example.calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import static com.example.calendar.Constants.CONTENT_URI;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CreateAppointment extends Activity implements OnClickListener{
private static String[] FROM = { _ID, DATE, TIME, TITLE, DETAILS};
private static String ORDER_BY = TIME + " ASC";
AppointmentsData appointments;
CalendarView calendar;
String string;
EditText nameTextBox;
EditText timeTextBox;
EditText detailsTextBox;
Button createButton;
SQLiteDatabase db;
Intent fetchDate = getIntent();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
createButton = (Button) findViewById(R.id.apptSave);
nameTextBox = (EditText)findViewById(R.id.apptName);//Assign the global name box
timeTextBox = (EditText)findViewById(R.id.apptTime);//Assign the global time box
detailsTextBox = (EditText)findViewById(R.id.apptDetails);//Assign the global details box
calendar = (CalendarView)findViewById(R.id.calendar);
createButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
string = "row";
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
private void addAppointment(String string) {
/* Insert a new record into the Events data
source. You would do something similar
for delete and update. */
String getTitle = nameTextBox.getText().toString();
String getTime = timeTextBox.getText().toString();
String getDetails = detailsTextBox.getText().toString();
db = appointments.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DATE, calendar.getDate());
values.put(TIME, getTime);
values.put(TITLE, getTitle);
values.put(DETAILS, getDetails);
getContentResolver().insert(CONTENT_URI, values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.apptSave:
addAppointment(string);
finish();
break;
}
}
}
The error is on the long dateFecth = fetchDate.getLongExtra(DATE, defaultValue); line and I don't know what to use for the second argument, since everything I think of gives me an error.
Can someone please help me with this?
Move fetchDate = getIntent(); inside onCreate method of Activity as:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
//.your code here..
fetchDate = getIntent(); // get intent here from previous Activity
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
First check - Value is associated with the given name.
if you don't want to use defaultValue try with bundle as follow
if (getchDate.hasExtra("Date")) {
Bundle bundle = new Bundle();
bundle = getchDate.getExtras();
Object object = bunlde.get(Date);
Now parse this object in your desire type.
}
You should check if result of getIntent() is not empty at first (an of course the call should be inside onCreate, not constructor). If it's not empty, then get long variable from it. defaultValue stands for a value returned from a method if a value for specified key is not found.

I can't create a Intent even if I import

Hello I'm new on android I have this trouble with my code
package com.example.spinner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
Spinner lista;
String[] datos = {"opcion1", "opcion2", "Ir a listView"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista = (Spinner) findViewById(R.id.lista1);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, datos);
lista.setAdapter(adaptador);
lista.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {
// TODO Auto-generated method stub
switch (i){
case 1:
Toast to = Toast.makeText(getApplicationContext(), datos[i], Toast.LENGTH_SHORT);
to.show();
break;
case 2:
Intent int = new Intent(MainActivity.this, VentanaListView.class);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
In the switch case 2 is where a litte box appears saying :
Intent cannot be resolved to a variable
I have already import the Intent using import android.content.Intent; and It says
The import android.content.Intent is never used
Please do you know what should I do?
Change this
Intent int = new Intent(MainActivity.this, VentanaListView.class)
to
Intent intent = new Intent(MainActivity.this, VentanaListView.class)
int is a keyword in java
You probably want to call startActivity(intent) also
You can't name a variable int; that's a keyword. Choose a different variable name, such as intent.
Intent int = new Intent(MainActivity.this, VentanaListView.class);
int is a reseverd word in java (a Keyoword) ,and it can not be used a variable`s name

Categories

Resources