connecting DB Mysql with android app using JSON & php - java

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!

Related

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

Connection refused Error displayed Android studio connect with Sql Server

I am creating a simple CRUD using Android Studio with Sqlserver. When I add data into the database I got the error ConnectionRefusedError.
I have attached the code below what I tried so far. I have been trying to connect the database for 2 two days but it hasn't let me.
I add the jar file successfully
jtds-1.2.7.jar
and I get the IP address of the SQL server and its port
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View"
/>
<EditText
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<EditText
android:id="#+id/course"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textMultiLine" />
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK" />
<Button
android:id="#+id/v1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View" />
</LinearLayout>
java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2;
Button b1,b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = findViewById(R.id.title);
ed2 = findViewById(R.id.course);
b1 = findViewById(R.id.btn1);
b2 = findViewById(R.id.v1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insert();
}
});
}
public void insert() {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectionUrl = "jdbc:jtds:sqlserver://192.168.84.2; databaseName=skill; port =0; user=sa; password=admin123";
Connection con = DriverManager.getConnection(connectionUrl);
PreparedStatement pst;
String title = ed1.getText().toString();
String description = ed2.getText().toString();
pst = con.prepareStatement("insert into course(coursename,fee)values(?,?)");
pst.setString(1, title);
pst.setString(2, description);
pst.executeUpdate();
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
ed1.setText("");
ed2.setText("");
ed1.requestFocus();
} catch (Exception ex) {
Toast.makeText(this, "Record Fail", Toast.LENGTH_LONG).show();
}
}
The ConnectionRefused error simply means that the host computer is refusing a connection on that port. Perhaps the port is blocked on the host's firewall? If you have access to the host, you can simply unblock the port. Please report back with what you find.

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

Cannot resolve method setText/getText

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

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

Categories

Resources