Parsing data or executing data Errror - java

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

Related

Detailed view on listview android

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.

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

Getting and Parsing JSON in the same Activity (Null Pointer Exception)

I want to get and parse json in the same activity but when I try to do this I get
Null Pointer Exception
I think I am getting this error because background task is slower than my code.
In My main activity:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new BackgroundTask().execute();
categoryAdapter = new CategoryAdapter(this,R.layout.row_layout);//I am sure,there is no problem in Category Adapter
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(categoryAdapter);
String id,kategori;
try {
Log.d("jsonstring",JSON_STRING); //I am getting error here JSON_STRING causes null pointer.
jsonObject = new JSONObject(JSON_STRING);
int count = 0;
jsonArray = jsonObject.getJSONArray("server_response");
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
kategori = JO.getString("kategori");
Categories categories = new Categories(id,kategori);
categoryAdapter.add(categories);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Categories contact = (Categories) listView.getItemAtPosition(position);
// Log.d("position",""+position);
// Log.d("id",""+id);
Log.d("id",contact.getId());
Log.d("kategori",contact.getKategori());
}
});
Background Task class:
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json_url= "exampleurl"; // I am sure, here is correct!
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine())!=null){
stringBuilder.append(json_string+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public BackgroundTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TextView textView = (TextView)findViewById(R.id.textView);
// textView.setText(result);
JSON_STRING = result;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I have Categories class with id and kategori attributes.
Finally How can I solve this problem? In fact I can parse after getting JSON.

I am trying to show data using api . but data is not showing in custom listView . list is empty

I am trying to show data in custom listView using API
there is no error but data is not shown in custom list .i made separate
class for asyncTask ,Adapters and model.
code of asyncTask is
public class CourseOutlinesTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
Context context;
private ArrayList<CourseModel> postList = new ArrayList<CourseModel>();
private ListView listView;
private View root;
TrainerCourseAdapter adapter;
String json_string;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//close process dialog
if (this.dialog != null) {
this.dialog.dismiss();
}
//parse json
try {
JSONObject jsonParse = new JSONObject(result);
JSONArray query = jsonParse.getJSONArray("courses");
for (int i = 0; i < query.length(); i++) {
try {
JSONObject jsonParser = query.getJSONObject(i);
CourseModel post = new CourseModel();
post.setId(jsonParser.getInt("id"));
post.setTitle(jsonParser.getString("title"));
post.setStatus(jsonParser.getString("status"));
post.setDescription(jsonParser.getString("description"));
System.out.println(post.getStatus()+"asdadasdad");
System.out.println(post);
postList.add(post);
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
}catch (Exception e) {
System.out.println(e);
}
// Parsing json
post.setDescription(obj.getString("description"));
// ****Handle CreationDate-Object
// Genre is json array
}
} else {
MyAppUtil.getToast(getApplicationContext(), message);
}*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
code of my adapter class is
public class TrainerCourseAdapter extends BaseAdapter {
private List list;
private Context context;
private static LayoutInflater inflater = null;
String [] cName;
String [] cDetail;
String [] created;
String [] cStatus;
TextView c_name,c_detail,c_date,c_status;
ArrayList<CourseModel> itemList;
Context mcontext;
public TrainerCourseAdapter(Context context,List list) {
mcontext = context;
itemList = (ArrayList<CourseModel>) list;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
public void setItemList(ArrayList<CourseModel> itemList) {
this.itemList = itemList;
}
public class Holder
{
TextView c_name;
TextView c_detail;
TextView c_date ;
Button c_status;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_courses_list, viewGroup,false);
this.c_name = (TextView) rowView.findViewById(R.id.txt_courseName);
this.c_detail = (TextView) rowView.findViewById(R.id.txt_courseDetail);
this.c_date = (TextView) rowView.findViewById(R.id.txt_courseDate);
this.c_status = (Button) rowView.findViewById(R.id.btn_courseStatus);
System.out.println("Mudassir Don");
final CourseModel data = itemList.get(i);
this.c_name.setText(data.getTitle());
this.c_detail.setText(data.getDescription());
this.c_status.setText(data.getStatus());
this.c_date.setText(data.getId());
System.out.println(c_date);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "You Clicked "+ cName[i], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
code of activity is
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
CourseOutlinesTask task = new CourseOutlinesTask();
task.execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
mylist = task.viewResult();
listView = (ListView) findViewById(R.id.course_listView);
listView.setAdapter(new TrainerCourseAdapter(CourseOutlinesActivity.this,mylist ) {
});
You need to assign your custom Adapter to listView.
yourListView.setAdapter(yourAdapter);
In your case, inside onPostExecute method of CourseOutlinesTask you should write it.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
Hope this helps.
You need to write a interface and get response in your activity and set adapter to list view
like.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
You can use callBack interface to get itemArraylist data to your activity class.
After getting itemlist data in activity class you can set adapter to listview.
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context, postList);
listView = (ListView) findViewById(R.id.course_listView);
listview.setAdapter(adapter);
// You can create interface in your CourseOutlinesClass with two method onSuccess() and onFailure() and in onPostExecute() send arraylist data using this interface to activity , then set adapter to fill data in listview.
Use the below code:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_outlines);
listView = (ListView) findViewById(R.id.course_listView);
new CourseOutlinesTask().execute("http://mantis.vu.edu.pk/bridging_the_gap/public/viewCourseOutlines");
}
and in postExecute of your AsyncTask setAdapter to listView
TrainerCourseAdapter adapter = new TrainerCourseAdapter(context,postList);
listView.setAdapter(adapter);

How to solve the error like java.lang.Throwable: setStateLocked?

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

Categories

Resources