I have a listView that shows properties name, and it works well, but I have problems with showing detailed view of each announcement. When you are clicking on items that are in listView, I am getting empty activity_details, and the following error occurs in the debugger:
W/System.err: org.json.JSONException: Value No of type java.lang.String cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at com.example.said.populate.DetailsActivity$GetHttpResponse.doInBackground(DetailsActivity.java:205)
W/System.err: at com.example.said.populate.DetailsActivity$GetHttpResponse.doInBackground(DetailsActivity.java:180)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:831)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
This is PHP file that used for connection:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$StudentID= $_POST['propertyid'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM estate2 where id = '$propertyid'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Here is my DetailsActivity provided below:
public class DetailsActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "https://sultonkhuja1111.000webhostapp.com/MobApp/detail.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,PHONE_NUMBER,CLASS;
String NameHolder, NumberHolder, ClassHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
NAME = (TextView)findViewById(R.id.textName);
PHONE_NUMBER = (TextView)findViewById(R.id.textPhone);
CLASS = (TextView)findViewById(R.id.textClass);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(DetailsActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(DetailsActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("propertyid",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("property_name").toString() ;
NumberHolder = jsonObject.getString("price").toString() ;
ClassHolder = jsonObject.getString("description").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
PHONE_NUMBER.setText(NumberHolder);
CLASS.setText(ClassHolder);
}
}
}
And ShowingAllEstatesActivity:
public class ShowingAllEstatesActivity extends AppCompatActivity {
ListView SubjectListView;
ProgressBar progressBarSubject;
String ServerURL = "http://sultonkhuja1111.000webhostapp.com/MobApp/Estate.php";
List<String> IdList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showing_all_estates);
SubjectListView = (ListView)findViewById(R.id.listview1);
progressBarSubject = (ProgressBar)findViewById(R.id.progressBar);
new GetHttpResponse(ShowingAllEstatesActivity.this).execute();
//Adding ListView Item click Listener.
SubjectListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowingAllEstatesActivity.this, DetailsActivity.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_listing, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.addNew:
startActivity(new Intent(this, AddPropertyActivity.class));
break;
}
return true;
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{
subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
IdList.add(jsonObject.getString("propertyid").toString());
subjects.SubjectName = jsonObject.getString("property_name");
subjectsList.add(subjects);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapter adapter = new ListAdapter(subjectsList, context);
SubjectListView.setAdapter(adapter);
}
}
}
}
This is code that is fetching for HttpUrl, detail.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$propertyid= $_POST['propertyid'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM estate2 where propertyid = '$propertyid'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
I think your HttpURL is not looking good. if this url not giving JSON response its will genrate same problem.
Related
I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'
I am calling an async task which returns a json object which has result,message as a string and result as cost.
Though it shows result,message string in the response object it shows json exception as no value for result.
Asynctask
public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
Context mContext;
private SearchPostsCallBack searchPostsCallBack;
private ProgressDialog loadingDialog;
private Snackbar snackbar;
private LinearLayout parentLayout;
private ArrayList<PostDelivery> list;
private JSONArray listsArray;
private JSONObject jsonObject;
public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {
this.mContext = context;
this.searchPostsCallBack = searchPostsCallBack;
this.parentLayout = linearLayout;
}
public interface SearchPostsCallBack {
void doPostExecute(ArrayList<PostDelivery> list);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = new ProgressDialog(mContext);
if (!isOnline()) {
snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
snackbar.show();
} else {
loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
}
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = mContext.getResources().getString(R.string.url) + "requestlist";
jsonParams = new JSONObject();
jsonParams.put("st_lati", params[0]);
jsonParams.put("st_longi", params[1]);
jsonParams.put("ed_lati", params[2]);
jsonParams.put("ed_longi", params[3]);
jsonParams.put("pt_date", params[4]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendPostRequest(params[5]);
} catch (JSONException je) {
Log.e("exception",je.toString());
return Excpetion2JSON.getJSON(je);
} catch (Exception ue) {
return Excpetion2JSON.getJSON(ue);
}
}
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if (loadingDialog.isShowing())
loadingDialog.dismiss();
try {
list = new ArrayList<>();
String result = response.getString("result");
String message = response.getString("message");
if (result.equals("1")) {
listsArray = response.getJSONArray("cost");
for (int j = 0; j < listsArray.length(); j++) {
jsonObject = listsArray.getJSONObject(j);
PostDelivery postDelivery = new PostDelivery();
postDelivery.setmPt_id(jsonObject.getString("pt_id"));
postDelivery.setmPt_name(jsonObject.getString("pt_name"));
postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
postDelivery.setmPtDate(jsonObject.getString("pt_date"));
list.add(postDelivery);
searchPostsCallBack.doPostExecute(list);
}
}
snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);
snackbar.show();
}catch (JSONException je) {
je.printStackTrace();
// Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Exception and response :
D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result
What is going wrong here? Please help.Thank you..
In your ServerResponse {"result":1}, the "result" is int, and you use String result = response.getString("result"), you should use getInt.
{"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung
mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
Form your attached response, it seems that the value of result is an int value and you are trying to get this value using:
String result = response.getString("result"); // WRONG
Try using:
int result = response.getInt("result");
I have this application the app bring data from database and store it in a list view then every record have a history i want when i click on the record in the ListView to show me the history of that record. for now i made it when i click on a record then click find id button it will give me the id of the record then i will click History to clear this ListView and showing the history of this record on the same ListView.
Screen Shot for the app1 ,
Screen Shot for the app2
Any one Can help me, my app run but when i want to show the history it don't pass this (if) i don't know why
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
the PHP side
<?php
$host='127.0.0.1';
$username='root';
$password='';
$database='app';
$con =mysqli_connect($host, $username, $password, $database) or die ('unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to connect to Database ".mysqli_connect_error();
}
$patientID = $_GET['patientID'];
$query= mysqli_query($con, "SELECT * FROM history where
patientID='$patientID' ");
if ($query)
{
while ($row = mysqli_fetch_array($query))
{
$flag[]= $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
HistoryDownloader Java Class
public class HistoryDownloader extends AsyncTask<Void, Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog progressDialog;
public HistoryDownloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//Before the job start
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching data .... Please wait ");
progressDialog.show();
}
#Override
protected String doInBackground(Void... strings) {
String data= downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null){
HistoryParser h= new HistoryParser(c,lv,s);
h.execute();
}else{
Toast.makeText(c, "Unable to download data ", Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is= null;
String line =null;
try{
URL url = new URL(address);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is =new BufferedInputStream( con.getInputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(is));
StringBuffer sb= new StringBuffer() ;
if(br !=null){
while((line=br.readLine()) !=null){
sb.append(line+"\n");
}
}
else{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
HistoryParser java Class
public class HistoryParser extends AsyncTask<Void, Integer, Integer> {
String lls;
Context c;
ListView lv;
String data;
ArrayList<String > patients= new ArrayList<>();
ProgressDialog progressDialog;
public HistoryParser (Context c, ListView lv, String data) {
this.c = c;
this.lv = lv;
this.data = data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing the data ... please wait");
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.histoParse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
// parse the reciv
private int histoParse (){
try {
//adding the data to json aray first
JSONArray js= new JSONArray(data);
//create json object to hold a singel item
JSONObject jo= null;
patients.clear();
// loop the array
for(int i=0 ;i<js.length();i++){
jo= js.getJSONObject(i);
//retriving the name
//TODO: write the strring depend on the column name in the database
// write the strring depend on the column name in the database
String case1=jo.getString("case1");
/* String case2=jo.getString("case2");
String case3=jo.getString("Case3");
String case4=jo.getString("Case4");
String case5=jo.getString("Case5");
String case6=jo.getString("Case6");
String case7=jo.getString("Case7");
String case8=jo.getString("Case8");
String case9=jo.getString("Case9");
String case10=jo.getString("Case10");
String trt1=jo.getString("trt1");
String trt2=jo.getString("trt2");
String trt3=jo.getString("trt3");
String trt4=jo.getString("trt4");
String trt5=jo.getString("trt5");
String trt6=jo.getString("trt6");
String trt7=jo.getString("trt7");
String trt8=jo.getString("trt8");
String trt9=jo.getString("trt9");
String trt10=jo.getString("trt10");
//add it to our array list
patients.add("Patient History");
patients.add("");
patients.add("Cases");
patients.add("");
*/ patients.add(case1);
/* patients.add(case2);
players.add(case3);
players.add(case4);
players.add(case5);
players.add(case6);
players.add(case7);
players.add(case8);
players.add(case9);
players.add(case10);
players.add("");
players.add("Treatments");
players.add("");
players.add(trt1);
players.add(trt2);
players.add(trt3);
players.add(trt4);
players.add(trt5);
players.add(trt6);
players.add(trt7);
players.add(trt8);
players.add(trt9);
players.add(trt10);
*/
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Main Class Java
public class MainActivity extends AppCompatActivity {
Context context;
String url="http://10.0.2.2/Android/Fetch.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView textView= (TextView) findViewById(R.id.textView);
final ListView lv=(ListView) findViewById(R.id.lv);
final Downloader d= new Downloader(this,url,lv);
String urlHistory="http://10.0.2.2/Android/History.php?patientID="+textView.getText().toString().trim();
final HistoryDownloader dd= new HistoryDownloader(this,urlHistory,lv);
final Button btn= (Button ) findViewById(R.id.button);
final Button btn2=(Button) findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setAdapter(null);
//String kk=textView.getText().toString().trim();
dd.execute();
if(textView.getText() != ""){
}else{
}
}
});
i did not use Transmitting Network Data Volley thats why im getting :)
Hi can you guys help me because I'm stuck here like forever and everytime I'm getting my JSON from my webhost its always null on my webhost and when I'm checking the string using Log.d this error shows NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object
Here are my codes.
PHP to get JSON
<?PHP
include_once("connection.php");
session_start();
$where = '';
if (isset($_GET['driverOwner']) && isset($_GET['roles']) && isset ($_GET['driverStatus'])){
$where = " WHERE driverOwner = '".addslashes($_GET['driverOwner'])."' AND roles = '".addslashes($_GET['roles'])."' AND driverStatus = '".addslashes($_GET['driverSTatus'])."'";
}
$query = "SELECT * FROM tbl_user ".$where."";
$result = mysqli_query($conn, $query);
if($result)
{
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
}
mysqli_close($conn);
?>
Drivers1.java
public class Drivers1 {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Connector
public class Connector {
public static HttpURLConnection connect(String urlAddress){
try{
URL url = new URL(urlAddress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//SET PROPERTIES
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner spDriver;
String jsonData;
ProgressDialog pd;
ArrayList<String> driver = new ArrayList<>();
public DataParser(Context c, Spinner sp, String jsonData) {
this.c = c;
this.spDriver = sp;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Please wait... Getting drivers");
pd.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0 ){
Toast.makeText(c, "Failed", Toast.LENGTH_SHORT).show();
}else {
//BIND
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1, driver);
spDriver.setAdapter(adapter);
spDriver.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(c, driver.get(i), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
private int parseData(){
try {
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
driver.clear();
Drivers1 s=null;
for (int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
int id=jo.getInt("userID");
String name=jo.getString("firstname");
s = new Drivers1();
s.setId(id);
s.setName(name);
driver.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner spDriver;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner spDriver) {
this.c = c;
this.urlAddress = urlAddress;
this.spDriver = spDriver;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch(Downloader)");
pd.setMessage("Please wait... Getting Drivers");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Downloader",""+ s);
pd.dismiss();
if (s == null) {
Toast.makeText(c, "Unable to retrieve", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(c, "Success!", Toast.LENGTH_SHORT).show();
//CALL PARSER CLASS TO PARSE
DataParser parser = new DataParser(c,spDriver,s);
parser.execute();
}
}
private String downloadData(){
HttpURLConnection con = Connector.connect(urlAddress);
if(con == null){
return null;
}
InputStream is=null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuffer response = new StringBuffer();
if (br != null) {
while ((line = br.readLine()) != null){
response.append(line+"\n");
}
}else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
And on the Activity with the spinner.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spDriver = (Spinner) findViewById(R.id.spDriver);
String url = "http://carkila.esy.es/carkila/getDriver.php?driverOwner="+ pref.getString("username","")+"&roles=driver&driverStatus=active";
new Downloader(InsertActivity.this,url ,spDriver).execute();
}
Sorry for the long post but please help me. :c thaaaaanks :)
EDIT
Error when Log.d("Downlaoder",s.toString()); is tested on Downloader.java.
Process: com.example.kun.carkila, PID: 31098
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.kun.carkila.mMySQL.Downloader.onPostExecute(Downloader.java:56)
at com.example.kun.carkila.mMySQL.Downloader.onPostExecute(Downloader.java:24)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
In your DataParser.Java class result 0 was return regardless.
private int parseData(){
try {
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
driver.clear();
Drivers1 s=null;
for (int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
int id=jo.getInt("userID");
String name=jo.getString("firstname");
s = new Drivers1();
s.setId(id);
s.setName(name);
driver.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0; //here it will go on
}
Please add a log to check what was returned, if it is returning 0 you must get Failed sort of toast.
I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);