So, I get some data from a nutrition database and I want to add a search option. I'm new to Android Studio so some advice would help me.
This is the app:
This edittext should search in the database and show after the name of products. Is there an easier way to make this work?
This is the activity layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NutritionDatabase">
<EditText
android:id="#+id/et_dataInput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Search Database"
android:inputType="textPersonName"
android:layout_marginTop="-58dp"
app:layout_constraintTop_toTopOf="#id/list"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="123dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="411dp"
android:layout_height="wrap_content"
android:background="#000000" />
<ImageView
android:id="#+id/back_to_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="40dp"
android:minHeight="45dp"
android:paddingTop="15dp"
android:src="#drawable/ic_back" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="Nutrition Database"
android:textAlignment="center"
android:textColor="#FFFFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
This is the java class:
package com.example.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class NutritionDatabase extends AppCompatActivity {
EditText et_dataInput;
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutrition_database);
et_dataInput=findViewById(R.id.et_dataInput);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(NutritionDatabase.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://wger.de/api/v2/ingredient/?language=2&limit=11865";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String name = c.getString("name");
String fat = c.getString("fat");
String protein = c.getString("protein");
String energy = c.getString("energy");
String carbohydrates = c.getString("carbohydrates");
String carbohydrates_sugar = c.getString("carbohydrates_sugar");
String fat_saturated = c.getString("fat_saturated");
String fibres = c.getString("fibres");
String sodium = c.getString("sodium");
// tmp hash map for single contact
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("name","Name :"+ name);
result.put("fat","Fat :"+ fat);
result.put("protein","Protein :"+ protein);
result.put("energy","Energy :"+ energy);
result.put("carbohydrates","Carbohydrates :"+ carbohydrates);
result.put("carbohydrates_sugar","Carbohydrates from sugar :"+ carbohydrates_sugar);
result.put("fat_saturated","Saturated Fat:"+ fat_saturated);
result.put("fibres","Fibres :"+ fibres);
result.put("sodium","Sodium :"+ sodium);
// adding contact to contact list
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(NutritionDatabase.this, resultList,
R.layout.list_item_nutrition, new String[]{ "name","fat","energy","protein","carbohydrates","carbohydrates_sugar","fat_saturated","fibres","sodium"},
new int[]{R.id.name, R.id.fat,R.id.protein,R.id.energy,R.id.carbohydrates,R.id.carbohidrates_sugar,R.id.fat_saturated,R.id.fibres,R.id.sodium});
lv.setAdapter(adapter);
}
}
}
This is the list that I use :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:paddingTop="10dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorAccent"
android:text="Name:"/>
<TextView
android:id="#+id/energy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:paddingTop="10dp"
android:text="Energy:"
/>
<TextView
android:id="#+id/protein"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Protein:"
/>
<TextView
android:id="#+id/carbohydrates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates:"
/>
<TextView
android:id="#+id/carbohidrates_sugar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates from sugar:"
/>
<TextView
android:id="#+id/fat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fat:"
/>
<TextView
android:id="#+id/fat_saturated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Saturated Fat:"
/>
<TextView
android:id="#+id/fibres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fibres:"
/>
<TextView
android:id="#+id/sodium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Sodium:"
/>
</LinearLayout>
Implements NutritionDatabase activity with Filterable class and implements Filterable class method in your NutritionDatabase activity.
#Override
public Filter getFilter() {
return myFilter;
}
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<String> tempList = new ArrayList<String>();
//constraint is the result from text you want to filter against.
//objects is your data set you will filter from
if (constraint != null && your_list != null) {
int length = your_list.size();
int i = 0;
while (i < length) {
String item = your_list.get(i);
//do whatever you wanna do here
//adding result set output array
tempList.add(item);
i++;
}
//following two lines is very important
//as publish result can only take FilterResults objects
filterResults.values = tempList;
filterResults.count = tempList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence contraint, FilterResults results) {
your_list = (ArrayList<String>) results.values;
if (results.count > 0) {
your_adapter.notifyDataSetChanged();
} else {
}
}
};
Implement your search edittext like
et_dataInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = et_dataInput.getText().toString());
your_adapter.getFilter().filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
use this code for search name from your list.
Related
so, I wrote a code where I get informations from a database about food.I'm asking If I can display some text with that ListView that I display.For example look here : app photo
Here are some numbers and I wanna write to all of them their description: Protein, Energy, etc.
Here is the code that I wrote :
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class LF1Activity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lf1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(LF1Activity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://wger.de/api/v2/ingredient/?language=2&limit=11865";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String name = c.getString("name");
String fat = c.getString("fat");
String protein = c.getString("protein");
String energy = c.getString("energy");
String carbohydrates = c.getString("carbohydrates");
String carbohydrates_sugar = c.getString("carbohydrates_sugar");
String fat_saturated = c.getString("fat_saturated");
String fibres = c.getString("fibres");
String sodium = c.getString("sodium");
// tmp hash map for single contact
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("name",name);
result.put("fat", fat);
result.put("protein",protein);
result.put("energy",energy);
result.put("carbohydrates", carbohydrates);
result.put("carbohydrates_sugar",carbohydrates_sugar);
result.put("fat_saturated", fat_saturated);
result.put("fibres",fibres);
result.put("sodium", sodium);
// adding contact to contact list
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(LF1Activity.this, resultList,
R.layout.list_item_nutrition, new String[]{ "name","fat","energy","protein","carbohydrates","carbohydrates_sugar","fat_saturated","fibres","sodium"},
new int[]{R.id.name, R.id.fat,R.id.protein,R.id.energy,R.id.carbohydrates,R.id.carbohidrates_sugar,R.id.fat_saturated,R.id.fibres,R.id.sodium});
lv.setAdapter(adapter);
}
}
}
Here is the activity where I display them all:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LF1Activity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="411dp"
android:layout_height="wrap_content"
android:background="#000000" />
<ImageView
android:id="#+id/back_to_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="40dp"
android:minHeight="45dp"
android:paddingTop="15dp"
android:src="#drawable/ic_back" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="Exercise Database"
android:textAlignment="center"
android:textColor="#FFFFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the list where I store them :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:paddingTop="10dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorAccent"
android:text="Name:"/>
<TextView
android:id="#+id/energy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:paddingTop="10dp"
android:text="Energy:"
/>
<TextView
android:id="#+id/protein"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Protein:"
/>
<TextView
android:id="#+id/carbohydrates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates:"
/>
<TextView
android:id="#+id/carbohidrates_sugar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates from sugar:"
/>
<TextView
android:id="#+id/fat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fat:"
/>
<TextView
android:id="#+id/fat_saturated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Saturated Fat:"
/>
<TextView
android:id="#+id/fibres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fibres:"
/>
<TextView
android:id="#+id/sodium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Sodium:"
/>
</LinearLayout>
try using
result.put("fat", "Fat :"+fat);
I am parsing a JSON and inflating the listview with it. First listview is showing the correct value but when i am opening another activity from my contributors button, second listview is not showing any value but displays a blank space where the text is to be displayed.
Here is my code...
Main Activity
package com.example.pc.jbossoutreachapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getStarted(View view)
{
Intent intent = new Intent(this, repositories.class);
startActivity(intent);
}
}
layout activity.main
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="358dp"
android:layout_height="251dp"
android:contentDescription="#string/ContentDescipt"
app:layout_constraintBottom_toTopOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/logo" />
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="31dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="#string/JBoss"
android:textColor="#android:color/holo_red_dark"
android:textSize="#dimen/size"
android:textStyle="bold"
app:fontFamily="sans-serif-smallcaps"
app:layout_constraintBottom_toTopOf="#+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_height="25dp"
android:gravity="center"
android:text="#string/JBoss_intro"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<Button
android:id="#+id/button"
android:layout_width="114dp"
android:layout_height="48dp"
android:background="#f0e68c"
android:onClick="getStarted"
android:text="#string/Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</android.support.constraint.ConstraintLayout>
repositories class
Here the code works fine and the items are shown in the listview
HttpHandler class makes service call and returns Json String.
package com.example.pc.jbossoutreachapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class repositories extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog ProgDialog;
private ListView listview;
private static String url = "https://api.github.com/orgs/JBossOutreach/repos";
ArrayList<HashMap<String,String>> RepoDetails;
public void link(View view)
{
TextView text = findViewById(R.id.Repolink);
String url = text.getText().toString();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
public void Contributors(View view)
{
listview = findViewById(R.id.list);
TextView name = findViewById(R.id.RepositoryName);
String n = name.getText().toString();
String url1 = "https://api.github.com/repos/JBossOutreach/"+n+"/contributors";
Intent intent = new Intent(this, contributors.class);
Bundle bundle = new Bundle();
bundle.putString("url", url1);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.repositories);
RepoDetails = new ArrayList<>();
listview = (ListView)findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgDialog = new ProgressDialog(repositories.this);
ProgDialog.setMessage("Please wait...");
ProgDialog.setCancelable(false);
ProgDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String Json_String = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + Json_String);
if(Json_String != null)
{
try
{
JSONArray array = new JSONArray(Json_String);
for(int i = 0; i < array.length(); i++)
{
JSONObject ob = array.getJSONObject(i);
String name = ob.getString("name");
JSONObject owner = ob.getJSONObject("owner");
String link = owner.getString("html_url");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contact.put("link", link+"/"+name);
RepoDetails.add(contact);
}
}
catch(final JSONException e)
{
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json Parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); }
});
}
}
else
{
Log.e(TAG, "Couldn't get Json from server");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server ", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(ProgDialog.isShowing())
{
ProgDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(
repositories.this, RepoDetails, R.layout.repo_list_item, new String[]
{"name", "link"}, new int[]{R.id.RepositoryName, R.id.Repolink});
listview.setAdapter(adapter);
}
}
}
repositories.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="109dp"
android:layout_marginLeft="109dp"
android:layout_marginTop="0dp"
android:text="#string/Heading1"
android:textSize="24sp"
android:textStyle="bold" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>
repo_list_itmen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/RepositoryName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingBottom="8dp"
android:textColor="#color/NameRepo" />
<TextView
android:id="#+id/Repolink"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="link"
android:paddingBottom="8dp"
android:textColor="#color/colorAccent" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Contributors"
android:text="#string/Contributors" />
</LinearLayout>
contributors class
Problem starts from here no items are displayed but only the blank space for the items are displayed.
package com.example.pc.jbossoutreachapp;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class contributors extends AppCompatActivity {
private String TAG = contributors.class.getSimpleName();
ArrayList<HashMap<String, String>> names;
ListView lv;
private ProgressDialog progressDialog;
static String url;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contributors);
names = new ArrayList<>();
lv = findViewById(R.id.list2);
Bundle bundle = getIntent().getExtras();
System.out.print(url);
url = bundle.getString("url");
new contributors.getcontrib().execute();
}
private class getcontrib extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(contributors.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
HttpHandler hd = new HttpHandler();
String Json_result = hd.makeServiceCall(url);
Log.e(TAG, "Response from url: " + Json_result);
if (Json_result != null) {
try {
JSONArray array = new JSONArray(Json_result);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String contributor_name = obj.getString("login");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", contributor_name);
names.add(hashMap);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json Parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(
contributors.this, names, R.layout.contributor_list_items, new String[]
{"contributors"}, new int[]{R.id.ContributorsName});
((SimpleAdapter) adapter).notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
}
contributors.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="109dp"
android:layout_marginLeft="109dp"
android:layout_marginTop="0dp"
android:text="#string/Heading2"
android:textSize="24sp"
android:textStyle="bold" />
<ListView
android:id="#+id/list2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>
contributors_list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/ContributorsName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingBottom="8dp"
android:textColor="#color/colorPrimaryDark" />
</LinearLayout>
Change your AsyncTask call from
new contributors.getcontrib().execute();
to
new getcontrib().execute();
Edit:
Also, change your adapter initialization code from:
ListAdapter adapter = new SimpleAdapter(
contributors.this, names, R.layout.contributor_list_items, new String[]
{"contributors"}, new int[]{R.id.ContributorsName});
to
ListAdapter adapter = new SimpleAdapter(
contributors.this, names, R.layout.contributor_list_items, new String[]
{"name"}, new int[]{R.id.ContributorsName});
Note: you have added your contributers name in "name" key and not in "contributors" key
Check Ur Response First .
String url1 = "https://api.github.com/repos/JBossOutreach/"+n+"/contributors";
Ur Json Respo
{
"message": "Not Found",
"documentation_url": "https://developer.github.com/v3/repos/#list-contributors"
}
I'm new to Android Studio and have some problems with running example code :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.abdul.moqueet.currency.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/et"
android:layout_marginTop="33dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:layout_alignTop="#+id/et"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert"
android:id="#+id/btn"
android:layout_marginTop="33dp"
android:layout_below="#+id/spin"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/usdtxt"
android:id="#+id/TextView1"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/eurtxt"
android:id="#+id/TextView2"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView1"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/inrtxt"
android:id="#+id/TextView3"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView2"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/usd"
android:layout_alignTop="#+id/TextView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/euro"
android:layout_above="#+id/TextView3"
android:layout_alignLeft="#+id/usd"
android:layout_alignStart="#+id/usd" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/inr"
android:layout_alignTop="#+id/TextView3"
android:layout_alignLeft="#+id/euro"
android:layout_alignStart="#+id/euro" />
</RelativeLayout>
MainActivity.java
package com.example.adriangranosik.coinconverter;
import android.os.AsyncTask;
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.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private EditText et;
private TextView usd, euro, inr;
private Button btn;
private Spinner spin;
private int index = 0;
private double inputvalue;
private String result[] = new String[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
usd = (TextView) findViewById(R.id.usd);
euro = (TextView) findViewById(R.id.euro);
inr = (TextView) findViewById(R.id.inr);
btn = (Button) findViewById(R.id.btn);
spin = (Spinner) findViewById(R.id.spin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
index = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usd.setText("wait...");
euro.setText("wait...");
inr.setText("wait...");
if (et.getText().toString().trim().length() > 0 && !et.getText().toString().trim().equals(".")) {
String textValue = et.getText().toString();
inputvalue = Double.parseDouble(textValue);
new calculate().execute();
}
}
});
}
public class calculate extends AsyncTask<String, String, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String[] doInBackground(String... params) {
if (index == 0) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR,USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject USDtojObj;
USDtojObj = new JSONObject(uRl);
JSONArray rateArray = USDtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 1) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD,EURINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject EurotojObj;
EurotojObj = new JSONObject(uRl);
JSONArray rateArray = EurotojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 2) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD,INREUR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject INRtojObj;
INRtojObj = new JSONObject(uRl);
JSONArray rateArray = INRtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String[] strings) {
if(index == 0){
double usdtoeuroval, usdtoinrval, usdtoeuroinp, usdtoinrinp, usdtousdinp;
usdtousdinp = inputvalue * 1;
usd.setText(""+usdtousdinp);
usdtoeuroval = Double.parseDouble(result[0]);
usdtoeuroinp = inputvalue * usdtoeuroval;
euro.setText(""+usdtoeuroinp);
usdtoinrval = Double.parseDouble(result[1]);
usdtoinrinp = inputvalue * usdtoinrval;
inr.setText(""+usdtoinrinp);
}else if(index == 1){
double eurotousdval, eurotoinrval, eurotousdinp, eurotoinrinp, eurotoeuroinp;
eurotoeuroinp = inputvalue * 1;
euro.setText(""+eurotoeuroinp);
eurotousdval = Double.parseDouble(result[0]);
eurotousdinp = inputvalue * eurotousdval;
usd.setText(""+eurotousdinp);
eurotoinrval = Double.parseDouble(result[1]);
eurotoinrinp = inputvalue * eurotoinrval;
inr.setText(""+eurotoinrinp);
}else if(index == 2){
double inrtousdval, inrtoeuroval, inrtousdinp, inrtoeuroinp, inrtoinrinp;
inrtoinrinp = inputvalue * 1;
inr.setText(""+inrtoinrinp);
inrtousdval = Double.parseDouble(result[0]);
inrtousdinp = inputvalue * inrtousdval;
usd.setText(""+inrtousdinp);
inrtoeuroval = Double.parseDouble(result[1]);
inrtoeuroinp = inputvalue * inrtoeuroval;
euro.setText(""+inrtoeuroinp);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
}
I am getting Following Errors :
layout/activity_main.xml
error: resource dimen/activity_vertical_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_vertical_margin) not found.
error: resource dimen/activity_horizontal_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_horizontal_margin) not found.
error: resource string/convert (aka com.example.adriangranosik.coinconverter:string/convert) not found.
error: resource string/usdtxt (aka com.example.adriangranosik.coinconverter:string/usdtxt) not found.
error: resource string/eurtxt (aka com.example.adriangranosik.coinconverter:string/eurtxt) not found.
error: resource string/inrtxt (aka com.example.adriangranosik.coinconverter:string/inrtxt) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
null
failed linking file resources.
I just wanna run a program to analyze source code. I know there is dimens.xml file which is missing but i have no clue what to put there.
I'm new in Android dev so i found example code just to learn how to create apps like that. But it's hard when i cannot run it :D
Thanks for your help.
you may just replace this
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
with smth like
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
(or if all 4 paddings are equal, you may set just android:padding="8dp")
In res -> Values put this code in dimens.xml
<dimen name="activity_vertical_margin">3dp</dimen>
Adjust dp according to your UI.
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
replace above code with below lines in RelativeLayout :
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
I tried everything but unable to disable that save button. i wrote it at the end of my onCreate.
Actually i wanted if user edits some notes and selects category from spinner it will automatically get enabled and i achieved it.
But i want that first when user is on this page button should be disabled. When user dose his work it will enable.
But how should i disable this save button.
Here is my OfflinePBDetails.java class
package passbookManager;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import logs.TraceLog;
import mainApplication.*;
import forbes.mPassbook.R;
import databaseClasses.DBAccountStatement;
import databaseClasses.DBCategoryMaster;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class OfflinePBDetails extends Activity implements OnItemSelectedListener
{
TextView tvDate;
TextView tvAmount;
TextView tvBalance;
TextView tvParticular;
TextView tvTitleAmount;
EditText etNotes;
Spinner spinnerCategory;
Button btnBack;
Button btnSave;
String file_Path;
Properties properties_config;
long sessionTimeout;
String passTransId;
String passDate;
String passParticular;
String passDebitCreditIndicator;
String passAmount;
String passTransString;
String passBalance;
String passFlag;
String transId;
String notes;
int countDBRows;
int countDBColumns;
String dbSubCategory;
String dbNotes;
String selectedCategory;
String[][] tableCategory ;
ArrayList<String> categoryIncome;
ArrayList<String> categoryExpense;
ArrayAdapter<String> adapterSelect;
DBCategoryMaster dbCMaster;
DBAccountStatement dbStatement;
TraceLog tc = new TraceLog();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ActionBar bar=getActionBar();
bar.hide();
setContentView(R.layout.activity_offline_pbdetails);
dbCMaster = new DBCategoryMaster(this);
dbStatement = new DBAccountStatement(this);
file_Path=Environment.getExternalStorageDirectory()+ "/Android/data/forbes.mPassbook/";
readConfigFileDetails();
if( Build.VERSION.SDK_INT >= 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try
{
tvDate = (TextView)findViewById(R.id.tv_getDate);
tvParticular = (TextView)findViewById(R.id.tv_getParticular);
tvAmount = (TextView)findViewById(R.id.tv_getAmount);
tvTitleAmount = (TextView)findViewById(R.id.tv_titleAmount);
tvBalance = (TextView)findViewById(R.id.tv_getBalance);
spinnerCategory = (Spinner)findViewById(R.id.spn_selectCategory);
etNotes = (EditText)findViewById(R.id.et_getNotes);
btnBack = (Button)findViewById(R.id.btnBack);
btnSave = (Button)findViewById(R.id.btnSave);
Intent intent = getIntent();
passTransId = intent.getExtras().getString("TransactionId");
passDate = intent.getExtras().getString("Date");
passParticular = intent.getExtras().getString("Particular");
passAmount = intent.getExtras().getString("Amount");
passTransString = intent.getExtras().getString("TransString");
passDebitCreditIndicator = intent.getExtras().getString("Indicator");
passBalance = intent.getExtras().getString("Balance");
passFlag = intent.getExtras().getString("FilterFlag");
tvDate.setText(passDate);
tvParticular.setText(passParticular);
tvTitleAmount.setText(passTransString);
if(tvTitleAmount.getText().equals("Withdrawal Amount"))
{
tvAmount.setTextColor(Color.RED);
}
else
{
tvAmount.setTextColor(Color.rgb(48,128,20));
}
String trimAmount = passAmount.trim();
String trimBalance = passBalance.trim();
tvAmount.setText(trimAmount);
tvBalance.setText(trimBalance);
etNotes.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
btnSave.setEnabled(true);
resetDisconnectTimer();
// Toast.makeText(getApplicationContext(), "After Typing", Toast.LENGTH_LONG).show();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
// Toast.makeText(getApplicationContext(), "Before Typing", Toast.LENGTH_LONG).show();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// Toast.makeText(getApplicationContext(), "Typing", Toast.LENGTH_LONG).show();
}
});
btnBack.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(passFlag.equalsIgnoreCase("OfflinePB"))
{
Intent i = new Intent(OfflinePBDetails.this,OfflinePB.class);
i.putExtra("filterFlag","notes");/**********Code to go back to DisplayFilter Page***************************/
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("notes"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","notes");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("transfer"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","transfer");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("cheque"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","cheque");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
});
btnSave.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
btnSave.setEnabled(false);
transId = passTransId;
notes = etNotes.getText().toString();
// if(spinnerCategory.length()==0)
// {
// spinnerCategory.setError("Please Enter mPIN ");
// mPin.requestFocus();
// }
// else
// if(notes.trim().length()==0)
// {
// etNotes.setError("Please Add Your Notes ");
// etNotes.setText(null);
// etNotes.requestFocus();
// }
if(dbStatement.updatePassbook(transId, selectedCategory, notes))
{
Toast.makeText(getApplicationContext(), "Data Updated Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "notes : " + notes, Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java Save.setOnClickListener():- "+e.toString());
}
}
});
dbGetCategoryList();
btnSave.setEnabled(false);
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java onCreate():- "+e.toString());
}
}
public void dbGetCategoryList()
{
int element;
try
{
Cursor rs = dbCMaster.getData();
countDBRows = rs.getCount();
countDBColumns = rs.getColumnCount();
tableCategory = new String[countDBRows][countDBColumns];
rs.moveToFirst();
for(element = 0; element < countDBRows; element++)
{
tableCategory[element][0] = rs.getString(0); // subCategory
tableCategory[element][1] = rs.getString(1); // Category
tableCategory[element][2] = rs.getString(2); // transType
rs.moveToNext();
// String finalData = tableCategory[element][0]+ " " + tableCategory[element][1]
// + " " + tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "finalData : " + finalData, Toast.LENGTH_SHORT).show();
}
rs.close();
showCategoryList();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java dbGetCategoryList():- "+e.toString());
}
}
public void showCategoryList()
{
int i = 0;
int j = 0;
int element;
String transType;
categoryIncome = new ArrayList<String>();
categoryExpense = new ArrayList<String>();
// categoryIncome = new String[2];
// categoryExpense = new String[3];
try
{
for(element = 0; element < countDBRows; element++)
{
transType = tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "transType : " + transType, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "passDebitCreditIndicator : " + passDebitCreditIndicator, Toast.LENGTH_SHORT).show();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-E"))
{
categoryExpense.add("Others");
}
else
{
categoryExpense.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryExpense : " + categoryExpense, Toast.LENGTH_SHORT).show();
i++;
}
}
else
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-I"))
{
categoryIncome.add("Others");
}
else
{
categoryIncome.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryIncome : " + categoryIncome, Toast.LENGTH_SHORT).show();
j++;
}
}
}
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryExpense);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryExpense);
}
else
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryIncome);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryIncome);
}
adapterSelect.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapterSelect);
spinnerCategory.setOnItemSelectedListener(this);
checkDBData();
if(dbSubCategory.equalsIgnoreCase("Others-E") || dbSubCategory.equalsIgnoreCase("Others-I"))
{
dbSubCategory = "Others";
}
ArrayAdapter myAdap = (ArrayAdapter) spinnerCategory.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(dbSubCategory);
//set the default according to value
spinnerCategory.setSelection(spinnerPosition);
etNotes.setText(dbNotes);
// to disable save button after notes is filled with note from db and item is selected from item listner
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java showCategoryList():- "+e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// try
// {
spinnerCategory.setSelection(position);
selectedCategory = (String) spinnerCategory.getSelectedItem();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-E";
}
// else
// {
// selectedCategory = selectedCategory;
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
else
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-I";
}
// else
// {
// selectedCategory = (String) spinnerCategory.getSelectedItem();
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
btnSave.setEnabled(true);
// switch (position) {
// case 0:
// // Whatever you want to happen when the first item gets selected
// break;
// case 1:
// // Whatever you want to happen when the second item gets selected
// break;
// case 2:
// // Whatever you want to happen when the thrid item gets selected
// break;}
// }
// catch(Exception e)
// {
// Toast.makeText(getApplicationContext(), "Exception onItemSelected : " + e, Toast.LENGTH_SHORT).show();
// }
}
public void checkDBData()
{
try
{
int element;
Cursor rs = dbStatement.getCategory(passTransId);
// int countCategoryRow = rs.getCount();
// int countCategoryColumn = rs.getColumnCount();
rs.moveToFirst();
dbSubCategory = rs.getString(13);
dbNotes = rs.getString(14);
rs.moveToNext();
// String reducedNotes = dbNotes.replace("\n", "").replace("\r", "");
//// String str =dbNotes.substring(0, 3);
// Toast.makeText(getApplicationContext(), "reducedNotes : " + reducedNotes, Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java checkDBData():- "+e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
public void readConfigFileDetails()
{
try
{
properties_config= new Properties();
FileInputStream fis2 = new FileInputStream(file_Path + "config.properties");
properties_config.load(fis2);
sessionTimeout = Long.parseLong(properties_config.getProperty("session_timeout"));
fis2.close();
}
catch(Exception e)
{
e.printStackTrace();
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java readConfigFileDetails():- "+e.toString());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed()
{
return;
}
public void onRestart()
{
finish();
super.onRestart();
startActivity(new Intent(this, Welcome.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
}
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg)
{
}
};
private Runnable disconnectCallback = new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "Session Expired", Toast.LENGTH_LONG).show();
System.out.println("Session Expired");
Intent intent = new Intent(getApplicationContext(),Welcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
};
public void resetDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, sessionTimeout);
}
public void stopDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction()
{
resetDisconnectTimer();
}
#Override
public void onResume()
{
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop()
{
super.onStop();
stopDisconnectTimer();
}
}
Here is my .xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bbk_base_all"
android:focusable="true"
android:focusableInTouchMode="true"
android:paddingRight="3dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/txtwelcome" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="130dp"
android:gravity="center" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleDate"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Transaction Date"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getDate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="30dp"
android:text="Date"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleParticulars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getParticular"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:ems="50"
android:gravity="left"
android:maxLines="4"
android:paddingLeft="30dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleAmount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getAmount"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleBalance"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Balance Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getBalance"
android:layout_width="125dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Balance"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleCategory"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Select Category"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<Spinner
android:id="#+id/spn_selectCategory"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleNotes"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Notes"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/et_getNotes"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_toLeftOf="#+id/imageView1"
android:hint="Add Your Own Notes"
android:maxLines="3"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" >
</EditText>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:gravity="center"
android:text="Transaction Details"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="24dp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/btnSave"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tableLayout1"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:background="#drawable/normalbuttonborder"
android:text="Save"
android:textSize="16sp"
android:textStyle="bold"
android:enabled="false" />
<Button
android:id="#+id/btnBack"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignBaseline="#+id/btnSave"
android:layout_alignBottom="#+id/btnSave"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/imageView1"
android:background="#drawable/normalbuttonborder"
android:text="Back"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Please help me.
Initially disable that Button after findViewById like this
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setEnabled(false);
The problem is you have Spinner where u enabling that Button. By default 1st item of Spinner is selected automatically and it is call in onCreate(...) and your Button gets enabled what you can do
Change logic of enabling that Button in Spinner's OnItemSelected(...) check if previously selected value and currently selected value is equal and EditText's value has not been changed then disable that Button otherwise enable that Button. Use boolean flag for this work.
You didnt disable your button before enabling it.
disble your button after declaring it.
btnSave.setEnabled(false);
Then enable it in your textChanged method
Since you want to disable your button use:
btnSave.setEnabled(false);
or try setting:
btnSave.setClickable(false);
along with setEnabled(false)
Alternatively, use below line in your xml:
android:clickable = "false"
android:enabled = "false"
and whenever user is done with note editing (i.e after selecting spinner item ) enable both(enabled & clickable) on btnSave according to your logic i.e use:
btnSave.setClickable(true);
btnSave.setEnabled(true);
I've been looking at this tutorial for how to use Spinners but I'm now stuck.
Currently when an item is selected from the spinner a toast is displayed with the choice, what I want to do instead is run a method to set the latitude and longitude to the selected country.
The button "Set Location to Japan" works perfectly by calling the method "SetLocationJapan". I just want take this process and put it into the spinner so whenever a choice is made the latitude and longitude is updated.
For example:
if Japan is selected in the spinner I want to call protected void setLocationJapan()
if France is selected I want to call protected void setLocationFrance()
if India is selected I want to call protected void setLocationIndia()
Code as requested:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
private Spinner spinner1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
addListenerOnSpinnerItemSelection();
findViewById(R.id.my_button).setOnClickListener(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
setLocationJapan = (Button) findViewById(R.id.SetLocationJapan);
getLocation = (Button) findViewById(R.id.GetLocation);
LongCoord = (TextView) findViewById(R.id.LongCoord);
LatCoord = (TextView) findViewById(R.id.LatCoord);
getLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When GetLocation button is clicked the showCurrentLocation
// function is ran
showCurrentLocation();
}
});
setLocationJapan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When SetLocation button is clicked the setCurrentLocation
// function is ran
setLocationJapan();
}
});
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
protected void setLocationJapan() {
// TODO Auto-generated method stub
LatCoord.setText("35.4112");
LongCoord.setText("135.8337");
}
protected void setLocationFrance() {
// TODO Auto-generated method stub
LatCoord.setText("65.4112");
LongCoord.setText("85.8337");
}
protected void setLocationIndia() {
// TODO Auto-generated method stub
LatCoord.setText("21.4112");
LongCoord.setText("105.8337");
}
protected void showCurrentLocation() {
// TODO Auto-generated method stub
// This is called to find current location based on GPS data and sends
// this to LongCoord and LatCoord TextViewsw
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
LongCoord.setText(Double.toString(longitude));
LatCoord.setText(Double.toString(latitude));
}
#Override
public void onClick(View arg0) {
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise")
.item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0)
.getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
CustomOnItemSelectedListener.java
package richgrundy.learnphotography;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SunriseSunset" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:entries="#array/country_arrays"
android:padding="10dp" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Date:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Current Date"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Location:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<Button
android:id="#+id/GetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Find Current Location" />
<Button
android:id="#+id/SetLocationJapan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Set Location to Japan" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate Sunrise/Sunset Time" />
<TextView
android:id="#+id/Sunrise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Sunset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Any help would be hugely appreciated, Thanks!
I'm pretty sure I need to move setLocationJapan() etc. inside the CustomOnItemSelectedListener class but don't know how to proceed from there.
I'd prefer pseudo code answers so I can work this out for myself if possible :)
This is a bit dirty, but you can pass your activity to CustomOnSelectedListener and then call those methods using the activity. Example:
public class CustomOnSelectedListener extends implements OnItemSelectedListener {
Activity mActivity;
CustomOnSelectedListener(Activity mActivity) {
this.mActivity = mActivity;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
if (mActivity instanceof SunriseSunset) {
SunriseSunset sunrise = (SunriseSunset) mActivity;
switch (pos) {
case 1: // Assuming Japan is first on your list
sunrise.setLocationJapan();
break;
... // fill in the rest here
}
}
}
... // rest of CustomOnSelectedListener here
}
However, this means all your setLocationJapan, setLocationIndia, etc. must change from protected to public so CustomOnSelectedListener can call them. Also, you must now instantiate CustomOnSelectedListener like this:
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener(this));