App isn't responding. Using ListActivity - android

When I try to launch application it closes before even shows something. I use ListActivity and I was using this site to write the code : Android ListActivity Example. I think everything is good in code. What can it be then?
public class MainActivity extends ListActivity {
static int kiekis, n = 10000, s = 20000, f = 30000, p1 = 40000, p2 = 50000, pozicija, i = 1;
ArrayList<String> list;
static String vardas;
static String numeris;
static String skype;
static String facebook;
static String papildoma1;
static String papildoma2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sprefs = getSharedPreferences("Prefs", MODE_PRIVATE);
list = new ArrayList<String>();
for (i = 1; i <= kiekis; i++) {
vardas = sprefs.getString(String.valueOf(i), "");
list.add(vardas);
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.list_view, R.id.vardas, list));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//String item = (String) getListAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, Detail.class);
pozicija = position;
SharedPreferences sprefs = getPreferences(MODE_PRIVATE);
numeris = sprefs.getString(String.valueOf(n + position), "");
skype = sprefs.getString(String.valueOf(s + position), "");
facebook = sprefs.getString(String.valueOf(f + position), "");
papildoma1 = sprefs.getString(String.valueOf(p1 + position), "");
papildoma2 = sprefs.getString(String.valueOf(p2 + position), "");
startActivity(intent);
finish();
}
}

Try putting break point on the First line and run in debug mode. Then you can see where it breaks

Related

Sending integers via Intent method

I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}
This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed

Getting Same Values For Two Different Keys in Shared Preferences

i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database
Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");
Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.

Cannot refer to a non-final variable myVariable inside an inner class defined in a different method

maybe i can't explain exactly my problem but with the code below i hope that helps you to answering my question. am trying to pass a String data between two Activities using Intent, in the same time, inside my StringRequest, i use jSonObject to recuperate data from server using volley, so i'd like to know how to put the sames variables recuperated from server to second activity using putExtra, because i have problem of modifier, if a remove modifier for my variables i have an error in the putExtra it should be final modifier and if i put it i have an error with my jsonobject, So, what's the solution please ? thank's in advance.
String idMed;
final String numTelMed;
final String communeMed;
final String nomMed;
final String emailMed;
final String codePostalMed;
final String prenomMed;
final String rueMed;
final String villeMed;
final String specialiteMed;
final String latitude;
final String longitude;
ListView listeView;
listeView = (ListView) findViewById(R.id.sampleListView);
List<String> listeMed = new ArrayList<String>();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1, listeMed);
listeView.setAdapter(adapter1);
JSONArray jObjectSearch = new JSONArray(response);
Log.i("OK","JSONObjectOK : "+jObjectSearch);
Log.i("OK","JSONObjectOK : "+jObjectSearch.getString(0));
for(int i=0; i<jObjectSearch.length();i++)
{
JSONObject j = new JSONObject(jObjectSearch.getString(0));
idMed = j.getString("id");
nomMed = j.getString("nomMed");
prenomMed = j.getString("prenomMed");
numTelMed = j.getString("numTelMed");
emailMed = j.getString("emailMed");
rueMed = j.getString("rueMed");
communeMed = j.getString("communeMed");
codePostalMed = j.getString("codePostalMed");
villeMed = j.getString("villeMed");
specialiteMed = j.getString("specialiteMed");
latitude = j.getString("latitude");
longitude = j.getString("longitude");
listeMed.add("Nom : "+nomMed+"\n "+"Prénom : "+prenomMed+"\n "+"Numéro Téléphone : "+numTelMed+"\n "
+"Email : "+emailMed+"\n "+"Adresse : "+rueMed+" "+codePostalMed+" "
+villeMed+" "+communeMed+"\n "+"Spécialité : "+specialiteMed);
listeView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
medecinSearched = new Intent(Main_Activity.this, MedecinSearched.class);
medecinSearched.putExtra("nomMed", nomMed);
medecinSearched.putExtra("prenomMed", prenomMed);
medecinSearched.putExtra("numTelMed", numTelMed);
medecinSearched.putExtra("emailMed", emailMed);
medecinSearched.putExtra("rueMed", rueMed);
medecinSearched.putExtra("communeMed", communeMed);
medecinSearched.putExtra("codePostalMed", codePostalMed);
medecinSearched.putExtra("villeMed", villeMed);
medecinSearched.putExtra("specialiteMed", specialiteMed);
medecinSearched.putExtra("latitude", latitude);
medecinSearched.putExtra("longitude", longitude);
startActivity(medecinSearched);
finish();
}
});
}
If you want to use a variable inside an anonymous class you have to use the final keyword.
However, in this case I would solve this with another approach:
Create a Med class with all the properties you need id, nom, prenom, etc.
Create a MedAdapter extending BaseAdapter instead of using an ArrayAdapter<String>.
onCreate method:
listeView = (ListView) findViewById(R.id.sampleListView);
listeMed = new ArrayList<Med>();
MedAdapter adapter1 = new MedAdapter<String>(Main_Activity.this, listeMed);
listeView.setAdapter(adapter1);
listeView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Med med = listeMed.get(position);
Intent medecinSearched = new Intent(Main_Activity.this, MedecinSearched.class);
medecinSearched.putExtra("EXTRA_MED", med); // Med must implement Serializable or Parcelable
startActivity(medecinSearched);
finish();
}
});
Response callback:
JSONArray jObjectSearch = new JSONArray(response);
for(int i=0; i<jObjectSearch.length(); i++) {
JSONObject jsonObject = new JSONObject(jObjectSearch.getString(0));
Med med = new Med(jsonObject); // Med must have a constructor which receives the JSONObject.
listeMed.add(med);
}
adapter1.notifyDataSetChanged();
Hope it helps.
thank's for All, it helps me so much
I have solution but i don't know if it has an inconvenient, here is my solution :
`
String idMed; String numTelMed; String communeMed;
String nomMed; String emailMed; String codePostalMed;
String prenomMed; String rueMed; String villeMed;
String specialiteMed; String latitude; String longitude;
ListView listeView;
listeView = (ListView) findViewById(R.id.sampleListView);
List<String> listeMed = new ArrayList<String>();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1, listeMed);
listeView.setAdapter(adapter1);
JSONArray jObjectSearch = new JSONArray(response);
Log.i("OK","JSONObjectOK : "+jObjectSearch);
Log.i("OK","JSONObjectOK : "+jObjectSearch.getString(0));
for(int i=0; i<jObjectSearch.length();i++)
{
JSONObject j = new JSONObject(jObjectSearch.getString(0));
final String idMedF = idMed = j.getString("id");
final String nomMedF = nomMed = j.getString("nomMed");
final String prenomMedF =prenomMed = j.getString("prenomMed");
final String numTelMedF =numTelMed = j.getString("numTelMed");
final String emailMedF =emailMed = j.getString("emailMed");
final String rueMedF= rueMed = j.getString("rueMed");
final String communeMedF =communeMed = j.getString("communeMed");
final String codePostalMedF = codePostalMed = j.getString("codePostalMed");
final String villeMedF =villeMed = j.getString("villeMed");
final String specialiteMedF =specialiteMed = j.getString("specialiteMed");
final double latitudeF = j.getDouble("latitude");
final double longitudeF = j.getDouble("longitude");
listeMed.add("Nom : "+nomMed+"\n "+"Prénom : "+prenomMed+"\n "+"Numéro Téléphone : "+numTelMed+"\n "
+"Email : "+emailMed+"\n "+"Adresse : "+rueMed+" "+codePostalMed+" "
+villeMed+" "+communeMed+"\n "+"Spécialité : "+specialiteMed);
listeView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
putData(idMedF, nomMedF, prenomMedF, numTelMedF, emailMedF, rueMedF, communeMedF, codePostalMedF, villeMedF, specialiteMedF, latitudeF, longitudeF);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}`

Problems with OnItemClick on a custom ListView

I am using a custom ListView with a custom ArrayAdapter for my custom object. I fill my ListView with parsed data from a xml file. I am able to fill the ListView with these data but I want to switch to different activities depending on which item was clicked. I can show with
int position
which item was clicked but how can I retrieve for example the name of the clicked button?
My code:
/**
* Setup
* */
#SuppressWarnings("unchecked")
private void setup() throws IOException {
device_array = new ArrayList<Device>();
//-----------------ACTIONBAR------------------------------------
//activates the default ActionBar
ActionBar actionBar = getActionBar();
actionBar.show();
// set the app icon as an action to go home
actionBar.setDisplayHomeAsUpEnabled(true);
//-------------------INTENT--------------------------------------
//get data from Intent
Intent intent = getIntent();
Name = intent.getStringExtra("Projectname");
IP = intent.getStringExtra("RouterIP");
URL = intent.getStringExtra("URL");
Port = intent.getStringExtra("Port");
//-------------------TEXTVIEWS+LISTVIEW---------------------------------------
nameproject = (TextView)findViewById(R.id.nameproject);
nameproject.setText("Projektname: "+Name);
routerip = (TextView)findViewById(R.id.routerip);
routerip.setText("KNX/IP-Router-Adresse: "+IP);
port = (TextView)findViewById(R.id.port);
port.setText(":"+Port);
url = (TextView)findViewById(R.id.url);
url.setText("URL: "+URL);
//Fill ListView
display_listview();
devices = (ListView)findViewById(R.id.deviceList);
adapter = new DeviceAdapter(this,
R.layout.listviewitem_device, device_array);
//add a view which is shown if the ListView is empty
devices.setEmptyView(findViewById(R.id.empty_list_view));
//Click on item in listview
devices.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ProjectView.this, OnOff.class);
i.putExtra("Uniqid","From_ProjectView_Activity");
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
devices.setAdapter(adapter);
//-------------------- READ ARRAYLIST-------------------------------
}
/**
* Insert Controls
* */
#SuppressWarnings("unchecked")
private void display_listview() {
//------------------ READ ARRAYLIST--------------------------------
//read ArrayList which is saved local
//change path to non-root folder
String filePath = context.getFilesDir().getPath().toString()+"/"+Name;
Log.d("FilestreamfromFolder", "Filepath:"+filePath+ " Projektname:"+Name);
File f = new File(filePath);
try
{
FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
XML = (ArrayList<Datapoint>) in.readObject();
Log.d("XML",XML.toString());
in.close();
fileIn.close();
} catch(IOException ioe)
{
ioe.printStackTrace();
return;
} catch(ClassNotFoundException c)
{
Log.d("FILESTREAM", ".Datapoint class not found.");
c.printStackTrace();
return;
}
//------------------ FILL DEVICE ARRAY FROM XML--------------------------------
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(ValueTemp)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.temperature_5));
Log.d("Temperature", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(ValueLux)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.brightness));
Log.d("Brightness", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(PercentScaling)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.lamp));
Log.d("Dimmer", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
//check XML file for datapoint 1.001 which demontrates a on/off switch
if (XML.get(i).getDptID().contains(OnOff)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.lamp_switch));
Log.d("OnOFF", d.getName().toString()+" added");
}
}
}
My Datapoint class:
package XMLParser;
import java.io.Serializable;
public class Datapoint implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4917183601569112207L;
private String stateBased;
private String name;
private String priority;
private String mainNumber;
private String groupadress;
private String dptID;
public Datapoint(){
}
public String getMainNumber() {
return mainNumber;
}
public void setMainNumber(String mainNumber) {
this.mainNumber = mainNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStateBased() {
return stateBased;
}
public void setStateBased(String stateBased) {
this.stateBased = stateBased;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getGroupadress() {
return groupadress;
}
public void setGroupadress(String group) {
this.groupadress = convert_groupadress(group);
}
public String getDptID() {
return dptID;
}
public void setDptID(String dptID) {
this.dptID = dptID;
}
#Override
public String toString() {
return "[[" + this.stateBased + "] ["+ this.name + "] [" + this.mainNumber + "]" + " [" + this.dptID
+ "] [" + this.priority + "] [" + this.groupadress + " ]]";
}
public String convert_groupadress(String groupadress) {
String groupaddress ="";
int grpadr = Integer.parseInt(groupadress);
int first = grpadr / 2048;
int first_res = grpadr-(first*2048);
int second = first_res / 256;
int second_res = first_res-(second*256);
int third = second_res / 1;
//int third_res = second_res-(third*32);
groupaddress = Integer.toString(first) +"/"+ Integer.toString(second) + "/"+ Integer.toString(third);
return groupaddress;
}
}
Calling the getItem(int position) method on your adapter will get the DataPoint for that position, so change your onItemClick method to be something like:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DataPoint point = (DataPoint) parent.getAdapter().getItem(position);
String pointName = point.getName();
// TODO: Launch an activity with that name or something.
}
I solved it this way:
//Click on item in listview
devices.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(device_array.get(position).getResImage()==R.drawable.brightness){
Intent i0 = new Intent(ProjectView.this, Brightness.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.temperature_5){
Intent i0 = new Intent(ProjectView.this, Temperature.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.lamp){
Intent i0 = new Intent(ProjectView.this, Dimmer.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.lamp_switch){
Intent i0 = new Intent(ProjectView.this, OnOff.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
}
});
Use the view , you are using to inflate the data in listview.
as i was using a textview.
here what i used,
TextView tv = (TextView) v.findViewById(R.id.contacts_name);
String savedname = tv.getText().toString();
here v is the argument that we get in the method
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{ // do something
}

Saving Android Preferences

Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}
In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)

Categories

Resources