Cannot resolve method setText/getText - java

So I am still learning Android and Java and I was trying to follow the code on this page: http://www.androidauthority.com/use-remote-web-api-within-android-app-617869/
The thing is that the code they provide does not work for me, and Android Studio says Cannot resolve method for both the setText and the getText methods.
This is my code:
package com.example.beldr.apitest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.example.beldr.apitest.R.id.emailText;
import static com.example.beldr.apitest.R.id.responseView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
private ProgressBar progressBar;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL("https://api.fullcontact.com/v2/person.json" + "email=" + email + "&apiKey=" + "126042055");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
And this is the activity_main.xml
<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.beldr.apitest.MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
tools:context="com.sample.foo.simplewebapi.MainActivity"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp">
<EditText
android:id="#+id/emailText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Enter email address"/>
<Button
android:id="#+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Search"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_centerHorizontal="true"
android:visibility="gone" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/responseView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
EDIT: I tried putting
TextView textView=(TextView)findViewById(R.id.responseView);
But then it says Cannot resolve method to the findViewById

TextView responseView = (TextView) findViewById(R.id.responseView);
then you'll be able to .setText() ect

The problem is that you are using those methods from ids and not from objects.
This should be the way:
EditText etEmail = (EditText) findViewById(R.id.emailText);
TextView tvResponse = (TextView) findViewById(R.id.responseView);
Then you can call getText() and setText() from etEmail and tvResponse.
Bonus: remove these lines
import static com.example.beldr.apitest.R.id.emailText;
import static com.example.beldr.apitest.R.id.responseView;
and just use:
import com.example.beldr.apitest.R

Put
TextView textView = (TextView) findViewById(R.id.responseView);
into onCreate() method and make variable TextView textView global in class, so then you can call it from AsyncTask

Related

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-some issue with running example code [dimens.xml]

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"

connecting DB Mysql with android app using JSON & php

I'm connecting to external database from my android application using PHP & JSON.
it's a simple login system , it vérify if the username and password exist on the DB so it go to the Main2activity but if diffrent user and pass it show a error message
I am successfully connected to database and getting results in browser,but while coming to android i'm not getting any results it is showing :
Error Parsing Data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray.
Below is my code:
MainActivity.java :
package com.example.hussienalrubaye.mysqlsystemlogin;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bulogin(View view) {
//get user name and password
EditText txtusername=(EditText)findViewById(R.id.etusername);
EditText txtpassword=(EditText)findViewById(R.id.etpassword);
new MyAsyncTaskresources().execute("http://l3pfe.byethost33.com/db.php?username="+txtusername.getText().toString()+"&password=" +txtpassword.getText().toString());
}
String result = "";
public class MyAsyncTaskresources extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream isr = null;
try{
String URL=params[0];
URL url = new URL( URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
}
catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
//parse json data
return null;
}
protected void onPostExecute(String result2){
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "login info : " + json.getString("id") + " " + json.getString("username") + " " + json.getString("password");
break;}
if(s.length()>0){
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
Intent in=new Intent(getApplicationContext(),Main2Activity.class);
startActivity(in);}
else
Toast.makeText(getApplicationContext(),"user name or password isnot correct",Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}
}
Main2Activity.java :
package com.example.hussienalrubaye.mysqlsystemlogin;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<EditText
android:hint="Enter user name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/etusername" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"></LinearLayout>
<EditText
android:hint="Enter password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/etpassword" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/button"
android:onClick="bulogin" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
activity_main2.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context="com.example.hussienalrubaye.mysqlsystemlogin.Main2Activity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main2" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
***content_main2.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"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main2"
tools:context="com.example.hussienalrubaye.mysqlsystemlogin.Main2Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="my control pannel"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
db.php :
<?php
mysql_connect("sql306.byethost33.com","b33_19513012","loool");//change server name //pass username according your settings
mysql_select_db("b33_19513012_pfe");// also chang the Mysql database name
$sql1=mysql_query("select * from admins WHERE username ='" . $_GET['username'] . "' and password='" . $_GET['password'] ."'"); //querstirng
if (!$sql1) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while($row=mysql_fetch_assoc($sql1))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>
Firt of all I'd like to warn you that mysql_connect is already deprecated, there is no mysql_connect anymore with PHP 7. Use mysqli instead.
As the mysql_connect doc says, you should specify the connection link. Check the $link variable.
$link = mysql_connect("sql306.byethost33.com", "b33_19513012", "loool");//change server name //pass username according your settings
mysql_select_db("b33_19513012_pfe", $link);// also chang the Mysql database name
$sql1 = mysql_query("select * from admins WHERE username ='" . $_GET['username'] . "' and password='" . $_GET['password'] . "'", $link); //querstirng
if (!$sql1) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error($link);
exit;
}
while ($row = mysql_fetch_assoc($sql1)) {
$output[] = $row;
}
print(json_encode($output));// this will print the output in json
mysql_close($link);
Good luck!

Why app crashes if user enter a simple text eg "hi"

Source are :
MainActivity.java-
package com.amostrone.akash.safebrowser;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.amostrone.akash.safebrowser.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view) {
Intent intent = new Intent(this, Browser.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
if(message == null || message.trim().equals("")) {
Toast.makeText(this, "No Input", Toast.LENGTH_SHORT).show();
message = "http://www.android.com"; // TODO Add your own WEBSITE
}
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
MainActivity.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:id="#+id/activity_main"
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.amostrone.akash.safebrowser.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textWebEmailAddress"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Search here." />
<Button
android:text="#string/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/button"
android:onClick="search" />
</RelativeLayout>
Browser.java
package com.amostrone.akash.safebrowser;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Browser extends AppCompatActivity {
static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
Intent intent = getIntent();
message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
if (!((message.substring(0, 11)).equals("http://www.") || (message.substring(0, 12)).equals("https://www.")))
check();
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(message);
}
void check() {
// WWW
if(message.substring(0,4).equals("www."))
{
message = "http://" + message;
return;
}
// Google Search
message = "https://www.google.co.in/search?q=" + message + "&rct=j" ;
}
}
Browser.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:id="#+id/activity_browser"
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.amostrone.akash.safebrowser.Browser">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
</RelativeLayout>
So my problem is that when i enter any text like "http://www.google.con.in" or just "www.google.co.in", everything works fine but when i enter just simple text like "stackoverflow" app crashes.It crashes even before system call the button "search" function "search(View view)".
Please help--
The problem may be that you are executing a substring on your message String, but it's too short.
As example:
message.substring(0, 11)
This will do a substring from index zero to 11, but what happens if the string have only a length of 4? There will be a exception.
You should extract the checks into an new method and do the length checks on the string before calling the substring method.
if(message.length() > 10){
message.substring(0,11);
}

Android TextView does not display russian symbols

I have a txt file (UTF-8 format) saved at res/raw. When I try to display it's contents in a TextView in my app, I get rubbish instead of russian symbols.
Here's the layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id = "#+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp"
android:padding="5dp"
android:text="#string/hello_world" />
</LinearLayout>
And my code:
package com.example.filereader_sample;
import java.io.DataInputStream;
import java.io.InputStream;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
InputStream file = getResources().openRawResource(R.raw.content);
try {
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(file);
String str = null;
while ((str = dataIO.readLine()) != null)
sBuffer.append(str + "\n");
text.setText(sBuffer.toString());
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG);
}
}
}
Is there any way to display russian symbols correctly?

Categories

Resources