Android-some issue with running example code [dimens.xml] - java

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"

Related

Search In Json Functionality

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.

Display text and json on activity Android Studio Java

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);

Listview not showinng the data but showinng the blank position where the value is to be shown

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"
}

Android studio - don't produce output

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"/>

Parsing sunrise and sunset values from web service

Okay, so it appears I'm stuck and could do with some help.
After successfully calling this webservice with my current longitude and latitude I am getting the entire xml file back in response.
However the only bit of the xml file I want is the sunrise and sunset times, how do I go about parsing these and only these into TextViews?
I've looked at and attempted countless tutorials on XmlPullParser, DOMParser and SAXParser and I'm now struggling.
Code as requested:
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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 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.EditText;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
findViewById(R.id.my_button).setOnClickListener(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
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();
}
});
}
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) {
EditText et = (EditText) findViewById(R.id.my_edit);
et.setText(results);
}
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
}
}
}
And here is the layout being used:
<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" >
<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: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:text="Today"
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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location:"
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:text="Current 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 Location" />
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate Sunrise/Sunset Time"
android:id="#+id/my_button"/>
<EditText
android:layout_margin="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="30"
android:maxLines="30"
android:textSize="12sp"
android:editable="false"
android:id="#+id/my_edit"/>
</LinearLayout>
Thanks in advance for your help!
You can try replacing your onPostExecute with the one below and add this import...
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(result));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
//EditText et = (EditText) findViewById(R.id.my_edit);
TextView tv = (TextView) findViewById(R.id.Date);
tv.setText("sunrise at "+doc.getElementsByTagName("sunrise").item(0).getTextContent() + " sunset at "+doc.getElementsByTagName("sunset").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
EDIT: I'm not sure which TextView you want to set but I guess this one (R.id.Date).
You can change the id if it's not the right one.
//EditText et = (EditText) findViewById(R.id.my_edit);
TextView tv = (TextView) findViewById(R.id.Date);
tv.setText...

Categories

Resources