i want to create an apps that can scan other ip that are connected to my Lan network. this is my java code,maybe there is an error that cause my codding don't produce the result.
package com.example.admin.ipscanner3;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
TextView tvWifiState;
TextView tvScanning, tvResult;
ArrayList<InetAddress> inetAddresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvWifiState = (TextView)findViewById(R.id.WifiState);
tvScanning = (TextView)findViewById(R.id.Scanning);
tvResult = (TextView)findViewById(R.id.Result);
//To prevent memory leaks on devices prior to Android N,
//retrieve WifiManager with
//getApplicationContext().getSystemService(Context.WIFI_SERVICE),
//instead of getSystemService(Context.WIFI_SERVICE)
WifiManager wifiManager =
(WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
tvWifiState.setText(readtvWifiState(wifiManager));
new ScanTask(tvScanning, tvResult).execute();
}
// "android.permission.ACCESS_WIFI_STATE" is needed
private String readtvWifiState(WifiManager wm){
String result = "";
switch (wm.getWifiState()){
case WifiManager.WIFI_STATE_DISABLED:
result = "WIFI_STATE_DISABLED";
break;
case WifiManager.WIFI_STATE_DISABLING:
result = "WIFI_STATE_DISABLING";
break;
case WifiManager.WIFI_STATE_ENABLED:
result = "WIFI_STATE_ENABLED";
break;
case WifiManager.WIFI_STATE_ENABLING:
result = "WIFI_STATE_ENABLING";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
result = "WIFI_STATE_UNKNOWN";
break;
default:
}
return result;
}
private class ScanTask extends AsyncTask<Void, String, Void> {
TextView tvCurrentScanning, tvScanResullt;
ArrayList<String> canonicalHostNames;
public ScanTask(TextView tvCurrentScanning, TextView tvScanResullt) {
this.tvCurrentScanning = tvCurrentScanning;
this.tvScanResullt = tvScanResullt;
}
#Override
protected void onPostExecute(Void aVoid) {
tvCurrentScanning.setText("Finished.");
tvScanResullt.setText("");
for(int i = 0; i < inetAddresses.size(); i++){
tvScanResullt.append(canonicalHostNames.get(i) + "\n");
}
}
#Override
protected Void doInBackground(Void... voids) {
scanInetAddresses();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
tvCurrentScanning.setText(values[0]);
}
private void scanInetAddresses(){
//May be you have to adjust the timeout
final int timeout = 500;
if(inetAddresses == null){
inetAddresses = new ArrayList<>();
}
inetAddresses.clear();
if(canonicalHostNames == null){
canonicalHostNames = new ArrayList<>();
}
canonicalHostNames.clear();
//For demonstration, scan 192.168.1.xxx only
byte[] ip = {(byte) 183, (byte) 171, (byte) 93, 0};
for (int j = 0; j < 255; j++) {
ip[3] = (byte) j;
try {
InetAddress checkAddress = InetAddress.getByAddress(ip);
publishProgress(checkAddress.getCanonicalHostName());
if (checkAddress.isReachable(timeout)) {
inetAddresses.add(checkAddress);
canonicalHostNames.add(checkAddress.getCanonicalHostName());
}
} catch (UnknownHostException e) {
e.printStackTrace();
publishProgress(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
publishProgress(e.getMessage());
}
}
}
}
}
this is my interface/ layout. i think there is no error here.
<?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"
tools:context="com.example.admin.ipscanner3.MainActivity">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.069" />
<TextView
android:id="#+id/WifiState"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.144">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scanning: " />
<TextView
android:id="#+id/Scanning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic" />
</LinearLayout>
<TextView
android:id="#+id/Result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.212" />
</android.support.constraint.ConstraintLayout>
i have add this two permission too to get a permission to access the wifi state and the internet.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
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 working on a tasks app, for which I created a list view that shows list items consitsting of task names, their priority etc. The data given to the list view is from an sqlite database. I, however, am unable to add more than one item to the list. I have no idea why. I have created a method to do so, but it doesn't seem to work. I don't know if the error is due to the database or my method itself. Even debugging didn't help. Please note that I am using a list adapter since I am using a custom listview.
Code for Activity where list is shown :
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
subtname = getIntent().getStringExtra("subtaskname");
pri = getIntent().getStringExtra("pri");
time = getIntent().getStringExtra("time");
// Using adapter for listview :
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
double working_hours = getIntent().getIntExtra("working_hours", 1);
double working_minutes = getIntent().getIntExtra("working_minutes", 0);
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
}
}
Code for Adapter Class :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).getPri() == "h")
{
ivPri.setImageResource(R.drawable.priority_high);
}
if (values.get(position).getPri() == "m")
{
ivPri.setImageResource(R.drawable.priority_med);
}
if (values.get(position).getPri() == "l")
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).getTime() == "more")
{
ivPri.setImageResource(R.drawable.time_symbol_more);
}
if (values.get(position).getPri() == "med")
{
ivPri.setImageResource(R.drawable.time_symbol_med);
}
if (values.get(position).getPri() == "less")
{
ivPri.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(SubtaskPartTwo newSubTask){
ArrayList<SubtaskPartTwo> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
XML code for listview activity :
<?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:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskSummary">
<!-- hello -->
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/okay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvTaskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Total Working Time (Including Breaks)"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/break_duration_mins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<!-- hello -->
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvWorktimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Work Time Before Each Break"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/hmm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreakAfterEvery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="Break Duration"
android:textColor="#B8AEAE"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/lvTaskList"
app:layout_constraintEnd_toStartOf="#+id/lvTaskList"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="30 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="16dp"
android:text="Start" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT : Database Code
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
dbHelper = new DBHelper(this);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = dbHelper.getdata();
while(res != null && res.moveToNext()){
subtname = res.getString(0);
pri = res.getString(1);
time = res.getString(2);
}
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("subtaskname", subtname);
intent.putExtra("pri", pri);
intent.putExtra("time", time);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete){
}
}
}
}
}
The problem is that you're creating a new ArrayList while the adapter is left using the old one. That's why notifyDataSetChanged() doesn't work because the adapter's backing list has not changed.
To fix this, update the values list directly
public void addANewSubTask(SubtaskPartTwo newSubTask) {
this.values.add(newSubTask);
notifyDataSetChanged();
}
or, add() through the adapter itself.
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
Even if I add one item, it shows 2 (both the same)
It seems you're adding the new element twice:
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
Just add via adapter only as it notifies as well. Check other places too for such duplicates.
i have provided a intent from the registration page to the add contacts page and in the add contacts page tried to add the details into the firebase database using two functions addusers() and addcontacts()
can somebody pls help me
this is my registration.java file
package universe.sk.syndriveapp;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class RegistrationActivity extends AppCompatActivity {
private EditText etName, etEmailsign, etPassign, etConfirmPassign, etBloodgroup, etDate;
private Button btn_register;
private TextView tvExist;
private FirebaseAuth firebaseAuth;
String name, email, password, bloodgrp, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("SIGN UP");
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String user_email = etEmailsign.getText().toString().trim();
String user_password = etPassign.getText().toString().trim();
//store in database:to be done after filling the contacts
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
startActivity(new Intent(RegistrationActivity.this, AddContacts.class));
//Toast.makeText(RegistrationActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(RegistrationActivity.this, "Registration Failed!", Toast.LENGTH_SHORT).show();
}
});
//startActivity(new Intent(RegistrationActivity.this,NavigationActivity.class));
}
}
});
tvExist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setupUIViews() {
etName = findViewById(R.id.etName);
etEmailsign = findViewById(R.id.etEmailsign);
etPassign = findViewById(R.id.etPassign);
btn_register = findViewById(R.id.btn_register);
tvExist = findViewById(R.id.tvExist);
etConfirmPassign = findViewById(R.id.etConfirmPassign);
etDate = (EditText) findViewById(R.id.etDate);
etBloodgroup = (EditText) findViewById(R.id.etBloodgroup);
}
private Boolean validate() {
Boolean result = false;
bloodgrp = etBloodgroup.getText().toString().trim();
date = etDate.getText().toString().trim();
name = etName.getText().toString();
password = etPassign.getText().toString();
email = etEmailsign.getText().toString();
String confirmpass = etConfirmPassign.getText().toString();
if (name.isEmpty() || password.isEmpty() || email.isEmpty()) {
Toast.makeText(this, "Please enter all the details!", Toast.LENGTH_SHORT).show();
} else {
if (password.equals(confirmpass))
result = true;
else
Toast.makeText(this, "Confirm password doesn't match with your password!", Toast.LENGTH_SHORT).show();
}
return result;
}
}
this is my addcontacts java file
package universe.sk.syndriveapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AddContacts extends AppCompatActivity {
Button registerbtn;
EditText etName,etEmailsign,etPassign,etBloodgroup,etDate;
EditText name1, num1, name2, num2, name3, num3;
String emname1,emname2,emname3;
String emnum1,emnum2,emnum3;
String name,email,password,bloodgrp,date;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontacts);
ActionBar actionBar = getSupportActionBar();
actionBar.setIcon(R.drawable.contacts);
actionBar.setTitle(" Add Emergency Contacts");
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
registerbtn= findViewById(R.id.registerbtn);
name1 = findViewById(R.id.name1);
num1 = findViewById(R.id.num1);
name2 = findViewById(R.id.name2);
num2 = findViewById(R.id.num2);
name3 = findViewById(R.id.name3);
num3 = findViewById(R.id.num3);
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int value=checkData();
if(value==1) {
emname1 = name1.getText().toString();
emnum1 = num1.getText().toString();
emname2 = name2.getText().toString();
emnum2 = num2.getText().toString();
emname3 = name3.getText().toString();
emnum3 = num3.getText().toString();
bloodgrp = etBloodgroup.getText().toString().trim();
date = etDate.getText().toString().trim();
name = etName.getText().toString();
password = etPassign.getText().toString();
email = etEmailsign.getText().toString();
adduser();
addcontacts();
/*
if (emname1.isEmpty() || emname2.isEmpty() || emname3.isEmpty()){
startActivity(new Intent(AddContacts.this, RegistrationActivity.class));
Toast.makeText(AddContacts.this, "", Toast.LENGTH_SHORT).show();
}
*/
Toast.makeText(AddContacts.this, "Registration Success!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddContacts.this, NavigationActivity.class));
}
}
});
}
boolean isEmpty(EditText text){
CharSequence str = text.getText().toString();
return TextUtils.isEmpty(str);
}
int checkData(){
if(isEmpty(name1) || isEmpty(name2) || isEmpty(name3) || isEmpty(num1) || isEmpty(num2) || isEmpty(num3)){
Toast.makeText(AddContacts.this,"Please fill all contact details",Toast.LENGTH_SHORT).show();
return -1;
}
else
return 1;
}
private void setupUIViews()
{
etName = findViewById(R.id.etName);
etEmailsign = findViewById(R.id.etEmailsign);
etPassign = findViewById(R.id.etPassign);
etDate =(EditText)findViewById(R.id.etDate);
etBloodgroup =(EditText) findViewById(R.id.etBloodgroup);
}
private void addcontacts(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseusers = firebaseDatabase.getReference(firebaseAuth.getUid());
Contactdetails contactdetails;
contactdetails = new Contactdetails(emname1,emname2,emname3,emnum1,emnum2,emnum3);
databaseusers.setValue(contactdetails);
}
private void adduser(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseusers= firebaseDatabase.getReference(firebaseAuth.getUid());
Userinfo user;
user = new Userinfo(name,email,date,bloodgrp);
databaseusers.setValue(user);
}
}
this is my userinfo java file
package universe.sk.syndriveapp;
import android.net.Uri;
import com.google.android.gms.tasks.Task;
public class Userinfo {
public String username;
public String uemail;
public String udate;
public String bloodgroup;
// public Uri imageUri;
public Userinfo(){
}
public Userinfo(String username, String uemail, String udate, String bloodgroup) {
this.username = username;
this.uemail = uemail;
this.udate = udate;
this.bloodgroup = bloodgroup;
// this.imageUri = imageUri;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUdate(){
return udate;
}
public void setUdate(String udate) {
this.udate = udate;
}
public String getBloodgroup() {
return bloodgroup;
}
public void setBloodgroup(String bloodgroup) {
this.bloodgroup = bloodgroup;
}
/* public Uri getImageUri() {
return imageUri;
}
public void setImageUri(Uri imageUri) {
this.imageUri = imageUri;
} */
}
this is my contactdetails java file
package universe.sk.syndriveapp;
public class Contactdetails {
public String cname1;
public String cname2;
public String cname3;
public String no1;
public String no2;
public String no3;
public Contactdetails(){
}
public Contactdetails(String cname1, String cname2, String cname3, String no1, String no2, String no3) {
this.cname1 = cname1;
this.cname2 = cname2;
this.cname3 = cname3;
this.no1 = no1;
this.no2 = no2;
this.no3 = no3;
}
public void setCname1(String cname1) {
this.cname1 = cname1;
}
public void setCname2(String cname2) {
this.cname2 = cname2;
}
public void setCname3(String cname3) {
this.cname3 = cname3;
}
public void setNo1(String no1) {
this.no1 = no1;
}
public void setNo2(String no2) {
this.no2 = no2;
}
public void setNo3(String no3) {
this.no3 = no3;
}
public String getCname1() {
return cname1;
}
public String getCname2() {
return cname2;
}
public String getCname3() {
return cname3;
}
public String getNo1() {
return no1;
}
public String getNo2() {
return no2;
}
public String getNo3() {
return no3;
}
}
this is my addcontacts xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="#string/hint_emname1"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num1"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_emname2"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num2"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_emname3"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num3"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/registerbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginTop="25dp"
android:background="#color/colorPrimary"
android:text="#string/hint_registerbtn"
android:textColor="#FFFFFF" />
</LinearLayout>
this is my profile xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".RegistrationActivity">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="#string/user_name"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.106" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/date_of_birth"
android:inputType="date" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etBloodgroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/blood_group"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etEmailsign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/email"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etDate" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etPassign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etEmailsign"
app:layout_constraintVertical_bias="0.08" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etConfirmPassign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etPassign"
app:layout_constraintVertical_bias="0.08" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#color/colorPrimary"
android:text="#string/next"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etConfirmPassign"
app:layout_constraintVertical_bias="0.132" />
<TextView
android:id="#+id/tvExist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:text="Already an existing member? Login"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_register" />
</LinearLayout>
finally this is my error log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at universe.sk.syndriveapp.AddContacts$1.onClick(AddContacts.java:67)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6237)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Your addcontacts.xml doesn't have an EditText with ID etBloodgroup
The line
bloodgrp = etBloodgroup.getText().toString().trim();
causes the error.
You haven't done a findViewById() on the EditText bloodgroup before and it also does not exist in the addcontacts.xml file. If you have defined it in another xml file, you won't be able to call it in an Activity not associated with the xml source (and you cannot associate more than one xml layout file to an Activity).
So the answer is basically: Define the EditText in the xml file associated to the Activity where you are trying to handle it.
I want to save the old state of checkbox With checkbox I want to update my data in database. When user changes the activity I lose his checked checkbox and when he again comes to that activity then every checkbox is unchecked and when he click to save with new values it will not saved because I set date as primary key in database. If I update the data with new values I lost my old data....
CheckBoxActivity.java
package com.example.shakeelmughal.assanislam;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0,vet=0;
Date date = new Date();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
mydb = new DatabaseHelper(this);
SharedPreferences settings = getSharedPreferences("mysettings", 0);
SharedPreferences.Editor editor = settings.edit();
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = (Button) findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertingData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor cr = mydb.getAllData();
if(cr.getCount() == 0)
{
showData("Error","No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (cr.moveToNext())
{
buffer.append("ID: "+cr.getString(0)+ "\n");
buffer.append("Fajar: "+cr.getString(1)+ "\n");
buffer.append("Zohr: "+cr.getString(2)+ "\n");
buffer.append("Asr: "+cr.getString(3)+ "\n");
buffer.append("Magrib: "+cr.getString(2)+ "\n");
buffer.append("Isha: "+cr.getString(3)+ "\n");
}
showData("Data",buffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
cb2.setChecked(true);
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
cb3.setChecked(true);
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
cb4.setChecked(true);
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
cb5.setChecked(true);
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date()
{
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
Its XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="com.example.shakeelmughal.assanislam.NamazCounterActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/namaz1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp"
android:layout_marginTop="50dp"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:button="#null"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz1"
android:layout_alignStart="#+id/namaz1"
android:layout_below="#+id/namaz1"
android:layout_marginTop="12dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz3"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz2"
android:layout_alignStart="#+id/namaz2"
android:layout_below="#+id/namaz2"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz4"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz3"
android:layout_alignStart="#+id/namaz3"
android:layout_below="#+id/namaz3"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz5"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz4"
android:layout_alignStart="#+id/namaz4"
android:layout_below="#+id/namaz4"
android:layout_marginTop="11dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz1"
android:layout_alignBottom="#+id/namaz1"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_toEndOf="#+id/result"
android:layout_toRightOf="#+id/result"
android:text="نمازِ فجر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView20"
android:layout_alignRight="#+id/textView20"
android:layout_alignTop="#+id/namaz2"
android:layout_marginTop="14dp"
android:text=" نمازِ ظہر / جمعہ"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:layout_alignTop="#+id/namaz3"
android:layout_marginTop="11dp"
android:text="نمازِ عصر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz4"
android:layout_alignBottom="#+id/namaz4"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:text="نمازِ مغرب"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView23"
android:layout_alignRight="#+id/textView23"
android:layout_alignTop="#+id/namaz5"
android:layout_marginTop="12dp"
android:text="نمازِ عشاء"
android:textColor="#000"
android:textSize="20sp"/>
<Button
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView24"
android:layout_centerHorizontal="true"
android:text="Save" />
<Button
android:id="#+id/dateee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView20"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/sumr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:text="View Summery" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
There could be many ways to do that, some of them are :
1. By using a File
2. By using shared preferences
I will recommend that latter one, a great implementation could be found by
Save CheckBox State to SharedPreferences File in Android
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"