This is my code for getting the data from JSON, it will contain only one row,
but it will give output for only "pro_name" for left of the values it will give just dots(......).
package com.example.sh_enterprises;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Detailes extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
public static String URL_PRODUCTS, pass1,pass2 ;
public static String ptopic,psubcode;
private static ProgressDialog progressDialog;
//a list to store all the products
List<pro_data> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailes);
Intent i = getIntent();
pass1 = i.getStringExtra("pro_id");
//Toast.makeText(this,"HI THIS IS "+pass,Toast.LENGTH_SHORT).show();
//URL_PRODUCTS = "https://premnathindia.000webhostapp.com/Api.php?p1="+pass;
URL_PRODUCTS = "http://192.168.225.25/prem/Api.php?p1="+pass1+"&p2=det";
Toast.makeText(this, URL_PRODUCTS, Toast.LENGTH_SHORT).show();
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
prefConfig product = new prefConfig(this);
String str = product.read_ret_id();
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < 1; i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
product.getString("pro_id");
String st;
TextView a = findViewById(R.id.pro_name);
TextView b = findViewById(R.id.weight);
TextView c = findViewById(R.id.base_amount);
TextView d = findViewById(R.id.mass_amonut);
TextView e = findViewById(R.id.brand);
TextView f = findViewById(R.id.catogery);
String st1 = product.getString("pro_name");
a.setText(st1);
st = product.getString("weight");
b.setText(st);
st = product.getString("total_amount");
d.setText(st);
//st = product.getString("pro_img_url");
st = product.getString("base_amount");
c.setText(st);
//st = product.getString("disc");
st = product.getString("brands");
e.setText(st);
st = product.getString("categories");
f.setText(st);
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void downme_ooi(View view) {
String pro_id = ((TextView) view).getText().toString();
Intent i = new Intent(this,Detailes.class);
i.putExtra("pro_id",pro_id);
startActivity(i);
}
public void go_back(View view) {
super.onBackPressed();
}
}
Sorry I made the Mistake that in TextView I put the text as password .
Related
I have created a project in which I am using spinner.
In spinner I am setting data fetched from MySql database. The data is being fetched properly as I can get the whole in the dropdown.
The problem is that spinner is not showing the selected value in the text area.
When I tested it with another arraylist of strings which was created in the program it was working.
I don't know why it is not working properly with the data fetched from database.
Kindly help me if you know the solution.
The java file is here when I used the data from MySql database
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
The java file is here when I used the arraylist created in the program.In this code the spinner is working fine
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
words.add("word1");
words.add("word2");
words.add("word3");
words.add("word4");
words.add("word5");
words.add("word6");
words.add("word7");
words.add("word8");
words.add("word9");
words.add("word10");
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,words);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
MySql file is here
<?php
include "config.php";
$sql="SELECT * FROM `$db`.`genderCategory`";
$result=mysqli_query($conn,$sql);
$categories['datas'] = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$data['id']=$row['0'];
$data['name']= $row['1'];
$data['image']=$row['2'];
array_push($categories['datas'],$data);
}
$categories['success']='1';
echo json_encode($categories);
mysqli_close($conn);
}else{
echo "No gender added";
}
?>
Finally , I have solved it by myself
The problem was that the method getGenders() was not getting the arrayAdapter
So , I defined it inside the method and booyah !! My problem got solved .
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayAdapter<String> myAdapter;
private final String url2 = "http://passkart.online/Z_getGender.php";
String gender ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
genderDrop.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
myAdapter.notifyDataSetChanged();
String item = parent.getItemAtPosition(position).toString();
genderDrop.setSelection(position);
gender = item;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"),
response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
//Array adapter is defined here ..........
myAdapter = new ArrayAdapter<String> (addSubCategory.this, R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
I am posting this answer for those who are still dealing with this error.
I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?
Can anyone shed some light on this for me? I'm buiding this app for my final project that's due on Friday. Head. is. FRIED.
Getting this error on build
C:\Users\Gary\AndroidStudioProjects\NatureAll.v2\app\src\main\java\com\example\gary\natureallv2\SearchAnimalActivity.java:58: error: incompatible types: int cannot be converted to String
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(POST,
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
It's telling me int can't be converted to string but I can't see where the int is. Here's my code:
package com.example.gary.natureallv2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Gary on 12/09/2016.Go Me
*/
public class SearchAnimalActivity extends AppCompatActivity{
EditText etSearchName;
Button btnSearch;
RequestQueue requestQueue;
String showUrl = "http://192.168.1.10/myDocs/mainProject/search_animal_and.php";
// String showUrl = "http://192.168.1.10/tutorial/showStudents.php";
TextView tvName;
TextView tvLatinName;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_animal_activity);
etSearchName = (EditText) findViewById(R.id.etSearchName);
tvName = (TextView) findViewById(R.id.tvName);
tvLatinName = (TextView) findViewById(R.id.tvLatinName);
tvDescription = (TextView) findViewById(R.id.tvDescription);
btnSearch = (Button) findViewById(R.id.btnSearch);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// System.out.println("ww");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray animals = response.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject animal = animals.getJSONObject(i);
//Change here for different string names
String name = animal.getString("name");
String latinName = animal.getString("latinName");
String description = animal.getString("description");
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
}
//result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
});
}
}
Many thanks in advance
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
You are trying to append a string to a View which has a value of its id (int). This wont work. you should instead call a .setText() on your view and set the text to its current value plus what you want to append.
I am trying to use the ProductHunt API to display a list of new posts in a ListView and further expand the list item on click.
On opening the app, the Progress bar appears but after that the app screen stays blank. I think there might be some error in my OnPostExecute method, because when I added a textview to display a string, its getting displayed but my listView is not getting displayed.
I used the standard Apache HttpClient for handling api requests.
I have 4 classes,
MainActivity.java
package com.emoji.apisoup;
/**
* Created by mdhalim on 16/05/16.
*/
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
public class MainActivity extends Activity {
private ListView lvPosts;
private ProductHuntAdapter adapterPosts;
public static final String POST_DETAIL_KEY = "posts";
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phunt_main);
String serverURL = "https://api.producthunt.com/v1/posts/";
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts = (ListView) findViewById(R.id.lvPosts);
lvPosts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
{
Intent i = new Intent(MainActivity.this, ProductHuntDetail.class);
i.putExtra(POST_DETAIL_KEY, adapterPosts.getItem(position));
startActivity(i);
}
}
});
new LongOperation().execute(serverURL);
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Content = new DefaultHttpClient();
private String Error = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(String... urls){
JSONArray items = null;
try {
HttpGet httpget = new HttpGet(urls[0]);
httpget.setHeader("Accept","application/json");
httpget.setHeader("Content-Type","application/json");
httpget.setHeader("Authorization","Bearer 2587aa878d7334e3c89794a6b73ebffb59a06c23b82cd0f789d2ab72d2417739");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String jsonStr = Content.execute(httpget, responseHandler);
Log.d("Response: ", "> " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray("posts");
// Parse json array into array of model objects
ArrayList<ProductHuntList> posts = ProductHuntList.fromJson(items);
// Load model objects into the adapter
for (ProductHuntList post : posts) {
adapterPosts.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
}
}
ProductHuntList.java containing the JSON Data model and deserializer and a static method for parsing an array of JSON
package com.emoji.apisoup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntList implements Serializable {
private static final long serialVersionUID = -8959832007991513854L;
private String name;
private String tagline;
private String screenshot_url;
private String largePosterUrl;
private String discussion_Url;
private String created_at;
private int votes_count;
public String getNames() {
return name;
}
public String getCreated_at() {
return created_at;
}
public String getScreenshot_url() {
return screenshot_url;
}
public String getDiscussion_Url() {
return discussion_Url;
}
public int getVotes_count() {
return votes_count;
}
public String getLargePosterUrl() {
return largePosterUrl;
}
public String getTagline(){
return tagline;
}
public static ProductHuntList fromJson(JSONObject jsonObject) {
ProductHuntList b = new ProductHuntList();
try {
// Deserialize json into object fields
b.name = jsonObject.getString("name");
b.created_at = jsonObject.getString("created_at");
b.tagline = jsonObject.getString("tagline");
b.screenshot_url = jsonObject.getJSONObject("screenshot_url").getString("300px");
b.largePosterUrl = jsonObject.getJSONObject("screenshot_url").getString("850px");
b.votes_count = jsonObject.getInt("votes_count");
b.discussion_Url = jsonObject.getString("discussion_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
// Return new object
return b;
}
public static ArrayList<ProductHuntList> fromJson(JSONArray jsonArray) {
ArrayList<ProductHuntList> posts = new ArrayList<ProductHuntList>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productJson = null;
try {
productJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
ProductHuntList post = ProductHuntList.fromJson(productJson);
if (post != null)
{
posts.add(post);
}
}
return posts;
}
}
ProductHuntAdapter.java this implements the ArrayAdapter
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntAdapter extends ArrayAdapter<ProductHuntList> {
public ProductHuntAdapter(Context context, ArrayList<ProductHuntList> aPosts) {
super(context, 0, aPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ProductHuntList posts = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_product_hunt, null);
}
// Lookup view for data population
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView created = (TextView) convertView.findViewById(R.id.created);
TextView tagline = (TextView) convertView.findViewById(R.id.tagline);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
name.setText(posts.getNames());
created.setText("Created On: " + posts.getCreated_at() + "%");
tagline.setText(posts.getTagline());
Picasso.with(getContext()).load(posts.getScreenshot_url()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
and finally, a class implementing the activity for Item Details when a user clicks on any item on the list.
ProductHuntDetail
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class ProductHuntDetail extends Activity {
private ImageView ivPosterImage;
private TextView name;
private TextView discusUrl;
private TextView upvotes;
private TextView tagline;
private TextView created;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_hunt_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
name = (TextView) findViewById(R.id.name);
discusUrl = (TextView) findViewById(R.id.discusUrl);
created = (TextView) findViewById(R.id.created);
upvotes = (TextView) findViewById(R.id.upvotes);
tagline = (TextView) findViewById(R.id.tagline);
// Load movie data
ProductHuntList posts = (ProductHuntList) getIntent().getSerializableExtra(MainActivity.POST_DETAIL_KEY);
loadMovie(posts);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(ProductHuntList posts) {
// Populate data
name.setText(posts.getNames());
upvotes.setText(Html.fromHtml("<b>Upvotes:</b> " + posts.getVotes_count() + "%"));
created.setText(posts.getCreated_at());
tagline.setText(posts.getTagline());
discusUrl.setText(Html.fromHtml("<b>Discussion Url:</b> " + posts.getDiscussion_Url()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(posts.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
I have been trying to debug this for hours :/
Your Async task is returning a void.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
As far as I can tell from the code, aPosts is empty.
I think your Async task should be -
AsyncTask<String, Void, ProductHuntAdapter>
and remove -
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
You are creating and updating this in your doInBackground() method already.
I got it!
I didnt need to declare these lines again in my onPostExecute() method
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
So bascially, my new onPostExecute() method goes like this
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lvPosts.setAdapter(adapterPosts);
}
I had been trying to find this error for last 2 hours, it was harder since, I wasn't even getting any errors. As soon as I posted it on StackOverFlow, seems like I had a divine intervention.
I am developing an android app which requires a "token" to login. This token is available along with some other details at https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin. I tried to fetch the data by JSON parsing but it is not working properly. Please help me. Thanks. This how I coded:-
//MainActivity.java
package com.example.login1;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity_old extends Activity {
//URL to get JSON Array
private static String url = "http://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
String token = null;
EditText userid, accesskey;
Button login;
TextView gettoken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
this.gettoken = (TextView)findViewById(R.id.lblToken);
new AsyncTask<Void, Void, Void>() {
JSONArray result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONArray(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Set JSON Data in TextView
gettoken.setText(token);
}
}.execute();
userid = (EditText) findViewById(R.id.txtUserid);
accesskey = (EditText) findViewById(R.id.txtPassword);
Button login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
/* This code get the values from edittexts */
String useridvalue = userid.getText().toString();
String accesskeyvalue = accesskey.getText().toString();
/*To check values what user enters in Edittexts..just show in logcat */
Log.d("useridvalue",useridvalue);
Log.d("accesskeyvalue",accesskeyvalue);
String md=md5(accesskeyvalue + token);
System.out.println(md);
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
});
}
}
"result" is JSONObject instead of JSONArray. get token String from result JSONObject as:
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
Just make these two changes.
result = json.getJSONArray(TAG_RESULT);
to
result = json.getJSONObject(TAG_RESULT);
and
JSONArray result;
to
JSONObject result;