First of all, i am quite a newbie to android and java as i come from a web developer background.
Recently, i had try to develop and app for learning purposes, but i am facing one headache problem during the development process.
i had a main activity that triggers Asynctask to get the list of id's from my wamp database through a php file.
Part of my main activity file - login_main.java
public class login_main extends AppCompatActivity implements OnDataSendToActivity{
ViewPager viewPager;
CustomAdapter adapter;
ArrayList<String> images = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String username = pref.getString("username", null);
String type = "getProfileImages";
RetrieveData retrieveData = new RetrieveData(this);
retrieveData.execute(type,username);
viewPager = (ViewPager) findViewById(R.id.view_pager);
}
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
String url = "http://192.168.12.252/"+id+"/profile.png";
images.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,images);//set ur image array here
viewPager.setAdapter(adapter);
}
AsyncTask file
public class RetrieveData extends AsyncTask<String,Void,String>{
Context context;
RetrieveData(Context ctx) {
context = ctx;
}
private OnDataSendToActivity dataSendToActivity;
public RetrieveData(Activity activity){
dataSendToActivity = (OnDataSendToActivity)activity;
}
#Override
protected String doInBackground(String... params) {
String profile_url = "http://192.168.12.252/getprofile.php";
String image_url = "http://192.168.12.252/imagelist.php";
String type = params[0];
if(type.equals("getProfile")){
try {
String user_name = params[1];
URL url = new URL(profile_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}else if(type.equals("getProfileImages")){
try {
String user_name = params[1];
URL url = new URL(image_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8")+"&"+URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
Page Adapter file
public class CustomAdapter extends PagerAdapter{
Activity activity;
ArrayList<String> images = new ArrayList<>();
LayoutInflater inflater;
public CustomAdapter(Activity activity, ArrayList<String> images){
this.activity = activity;
this.images = images;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.swipe,container,false);
ImageView image;
image = (ImageView)itemView.findViewById(R.id.imageView);
DisplayMetrics dis = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
int height = dis.heightPixels;
int width = dis.widthPixels;
image.setMinimumHeight(height);
image.setMinimumWidth(width);
try{
Picasso.with(activity.getApplicationContext())
.load(images.get(position))
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}catch (Exception ex){
}
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View)object);
}
}
So let me explain a little bit here, whats going on here. What my app does is it will get array of ids from my phpmysql, after it get from asynctask, it send the data back to main activity using Interface which is the sendData function in main from that sendData function you can see there is a loop to loop through each id and generate a url image link and store it into a string array which the variable name is images and the page adapter will put the image into imageView in the page adapter with Picasso pluggin.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
String url = "http://192.168.12.252/"+id+"/profile.png";
images.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,images);//set ur image array here
viewPager.setAdapter(adapter);
The problem is i want to make those image clickable and when it click, it will display the information for that particular id, how do map the id with those image and make them clickable and when it clicks , it do another asynctask to retrieve more detail information of that id
You can alter your Adapter class to take in an ArrayList of Ids as well:
public class CustomAdapter extends PagerAdapter{
ArrayList<String> mIds = new ArrayList<>();
public CustomAdapter(Activity activity, ArrayList<String> images, ArrayList<String> ids){
mIds = ids;
}
Then, inside your instantiateItem():
image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String clickedId = mIds.get(position);
// Do something with the selected image Id
}
});
Don't forget to change your call to new CustomAdapter(activity, images, ids) though.
I suggest that you create your own Object (Class) that have item (id, filename, ...). Pass your ArrayList<YourObjectName> into CustomAdapter.
Related
Im new to android development have very basic knowledge of this whatever i have achieved till now is achieved using this website or youtube videos i'm stuck in AsyncTask (Earlier i was using .get() on Create View and it was working fine but UI Was blocked until task is finished. To Avoid UI Blocking i was advice to remove .get() function from OnCreateView() function now after removing this im not being able to get any data from AsyncTask). I did that but now i'm not being able to create view i did lots of research but unable to get this strength
Here is my Codes Please Help how to create view from this
OnCreateView() :-
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
GridView gridView = (GridView) GView.findViewById(R.id.gridView);
//Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
String finalResult = null;
try{
finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
JSONObject parentObject = null;
parentObject = new JSONObject(finalResult);
if(((String) parentObject.names().get(0)).matches("error")){
JSONObject jObj = parentObject.getJSONObject("error");
errorThrow(jObj.getString("Description"));
} else if(((String) parentObject.names().get(0)).matches("success")){
JSONObject jObj = parentObject.getJSONObject("success");
JSONArray arrajson = jObj.getJSONArray("data");
String arrayCount = Integer.toString(arrajson.length());
String[] type = new String[arrajson.length()];
Integer[] count = new Integer[arrajson.length()];
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
type[i] = jsonObject.getString("type");
count[i] = jsonObject.getInt("count");
}
CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
gridView.setAdapter(customAdpter);
return GView;
}
} catch (JSONException e) {
e.printStackTrace();
}
return GView;
}
Base Adapter Code :-
class CustomAdpter extends BaseAdapter {
String[] type;
Integer[] count;
public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
this.count = count;
this.type = type;
}
#Override
public int getCount() {
return type.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
TextView textView = (TextView) view.findViewById(R.id.TextView1);
TextView textView1 = (TextView) view.findViewById(R.id.textView2);
textView.setText(String.valueOf(count[i]));
textView1.setText(type[i]);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AsyncTask Code :-
public class JSONTask extends AsyncTask<String,String,String> {
private ProgressDialog mProgressDialog;
int progress;
public JSONTask(){
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
#Override
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
final String finalJson = params[1];
String json = finalJson;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("A-APK-API", "******");
connection.setRequestProperty("Authorization", "Basic **:**");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
OutputStream stream = connection.getOutputStream();
OutputStreamWriter streams = new OutputStreamWriter(stream, "UTF-8");
stream.write(json.getBytes("UTF-8"));
stream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
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;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Json_String = result;
Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
Please help me here
You cannot get a result from asynctask when you dont use .get().
So change that statement. Start only the asynctask.
Then put all the code after that line in onPostExecute() of the AsyncTask.
Thats all.
you should change way you are creating the Adapter and attaching
you should do this
1.At first get the data in List,ArrayList etc. via AsyncTask, doInBackGround method
then on the onPostExecute method retrieve the data and create Adapter and attach it to your View
While you are getting data you can show some ProgressDialog.
If your AsyncTask is in other separate class then use interface to get the data from your AsyncTask class
look at this https://stackoverflow.com/a/47373959/8197737
Before trying to get a row of data from a MySQL server, I used a column and managed to get that into a listView through tutorials. But for getting data in a row from a table, I couldn't manage to put it into a listView.
So what I'm trying to do is put "shift" from background worker into a listview.
PHP SQL query:
$sql = "SELECT id, employee, hours FROM selected_shifts WHERE day = '$day';";
Navigation drawer from Main Activity:
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
if (items[0].equals(mExpandableListTitle.get(childPosition))) {
String day = "Monday";
OnChoice(day);
} else if (items[1].equals(mExpandableListTitle.get(childPosition))) {
String day= "Tuesday";
OnChoice(day);
} else if (items[2].equals(mExpandableListTitle.get(childPosition))) {
String day = "Wednesday";
OnChoice(day);
} else if (items[3].equals(mExpandableListTitle.get(childPosition))) {
String day = "Thursday";
OnChoice(day);
} else if (items[4].equals(mExpandableListTitle.get(childPosition))) {
String day = "Friday";
OnChoice(day);
}
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
public void OnChoice(String day) {
String type = "choice";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, day);
}
Background worker(getting data from MySQL server):
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String shifts_url = "***PHP LINK***";
if(type.equals("choice")) {
try {
String day = params[1];
URL url = new URL(shifts_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("day","UTF-8")+"="+URLEncoder.encode(day,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String shift="";
String line="";
while((line = bufferedReader.readLine())!= null) {
shift += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return shift;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String shift) {
//Toast the data as json
Toast.makeText(context, shift, Toast.LENGTH_LONG).show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
EDIT
Putting it into ListView:
public void onTaskCompleted(String shift) {
try {
loadIntoListView(shift);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadIntoListView(String shift) throws JSONException {
JSONArray jsonArray = new JSONArray(shift);
String[] list = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
list[i] = obj.getString(shift);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
So what you want to do to pass the shift back is use a custom "Listener".
Create this
public interface TaskListener {
void onTaskCompleted(String shift);
}
And on your BackgroundWorker change the constructor as follow:
TaskListener taskListener;
BackgroundWorker(Context context, TaskListener taskListener){
this.context = context;
this.taskListener = taskListener;
}
Then on the onPostExecute method, do a taskListener.onTaskCompleted(shift).
When you call the BackgroundWorker constructor pass this as the second parameter:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, this)
Then implement TaskListener on your Main and implement the method.
Something like this:
... MainActivity implements TaskListener
...
#override
onTaskCompleted(String shift) {
// You have your `shift` here to do with as you please
}
At your onPostExecute() you should add the "shift" to a dataSet in your adapter.
I had a problem here.
I have a login_activity that execute asynctask to get some result from a php file which it connects to mysql database.
public class login_main extends AppCompatActivity implements OnDataSendToActivity{
ViewPager viewPager;
CustomAdapter adapter;
ArrayList<String> image = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
String type = "getProfileImages";
RetrieveData retrieveData = new RetrieveData(this);
retrieveData.execute(type);
//After Asycntask, get the result and put back into image array
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new CustomAdapter(login_main.this,image);
viewPager.setAdapter(adapter);
}
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When i get the result i try to process the result by using interface from the asynctask
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
Everything is working fine except that the image array always empty when i pass it to the PageAdapter. How can i pass the data back to activity from asycntask and push into the array image, by using interface, it cant work.
Or anyway i can directly process it in Asyntask and update the ViewPager.
Here is my Asynctask
public class RetrieveData extends AsyncTask<String,Void,String>{
Context context;
RetrieveData(Context ctx) {
context = ctx;
}
private OnDataSendToActivity dataSendToActivity;
public RetrieveData(Activity activity){
dataSendToActivity = (OnDataSendToActivity)activity;
}
#Override
protected String doInBackground(String... params) {
String profile_url = "http://192.168.12.252/getprofile.php";
String image_url = "http://192.168.12.252/imagelist.php";
String type = params[0];
if(type.equals("getProfile")){
try {
String user_name = params[1];
URL url = new URL(profile_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}else if(type.equals("getProfileImages")){
try {
URL url = new URL(image_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
The execution sequence is all messed up. by the time ur adding data to ur image array the,the empty image array has already been passed to the view pager adapter,therfore ur image array is empty.
u continue to do the same thing but instead of setting view pager adapter in onCreate() set the adapter after u call the method sendData();
modify the sendData() method like this.
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,image);//set ur image array here
viewPager.setAdapter(adapter);
}
I have been wanted to display multiple data retrieve in a list view. However when i used array adapter, i have been facing this problem. How should i solve it? This is the class where i get my data and i store it in an array list. The array list will later be call in another class to put it in array adapter.
public class connect2 extends AsyncTask<String, Void, String>{
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
View view;
Activity activity;
public static final String SEARCH = "product_img1";
ArrayList<String> list = new ArrayList<String>();
ContactObjects co = new ContactObjects();
Bitmap bitmap;
public connect2(Activity activity, View v) {
this.activity = activity;
view = v;
}
String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
protected String doInBackground(String... arg0) {
String ipAddress = "http://192.168.43.214/apexStore2/";
try {
URL url = new URL(ipAddress +"image1.php");
String urlParameters =
URLEncoder.encode("cat_id", "UTF-8") + "=" +
URLEncoder.encode(arg0[0], "UTF-8") + "&" +
URLEncoder.encode("product_img1", "UTF-8") + "=" +
URLEncoder.encode("???", "UTF-8");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
//System.out.println(response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
for(int i = 0; i < uniObject.length(); i++) {
JSONObject rowObject = uniObject.getJSONObject(i);
//EventObject co = new EventObject();
co.img1 = ipAddress +"img/products/" +
rowObject.getString("product_img1");
//mContentItems.add(co);
System.out.println("hi" +co.title);
list.add(co.img1);
}
//To further break down JSON
//JSONObject oneObject = mainObject.getJSONObject("1");
//String id = oneObject.getJSONObject("id");
try{
}
finally{
connection.disconnect();
}
} catch (Exception e){
System.out.println(e.toString());
}
return "";
}
protected void onPreExecute(){
}
#Override
protected void onPostExecute(String result){
Intent intent = new Intent(view.getContext(), CatalogActivity.class);
intent.putExtra(SEARCH, list);
activity.startActivity(intent);
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
public LoadImage(ImageView img){
this.img = img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new
URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}else{
}
}
}
}
This is the class where i call the data and put it in array adapter.
public class CatalogActivity extends Activity {
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Create the list
ListView listViewCatalog = (ListView)
findViewById(R.id.ListViewCatalog);
setContentView(R.layout.item);
new connect2 (this,
this.findViewById(android.R.id.content)).execute("3");
Intent intent = getIntent();
String search = intent.getStringExtra(connect2.SEARCH);
adapter = new ArrayAdapter<String>(this, R.layout.item,
R.id.ImageViewItem, search);
listViewCatalog.setAdapter(adapter);
}
}
The problem seems to be that you're using an ImageView's resource ID while ArrayAdapter takes only TextView as resource ID.
EDIT- Since your string is nothing but text, the container can't be an ImageView.
Another EDIT- You need to pass a List of strings as a parameter as the 4th parameter. Add this as the 4th parameter instead:- new String[]{search}
I am new to Android Studio and have a simple android view i am working on. A button click makes a call to the foursquare API and get backresults for starbucks around my location that I parse and am trying to set to the adapter for the listbox on the same view. If i put a breakpoint in the OnPostExecute() I see the mFoursquare adapter that I set for the listview has two json string results in the mFoursquareAdapter , I even call the
mFoursquareAdapter.notifyDataSetChanged();
in it but the view does not get refreshed with the results. I have posted the code below. Can anyone please point out what I am doing wrong or need to change since I already have the results and need to get this done...Your help and feedback very much appreciated! thanks
public class FoursquareInfoFragment extends android.app.Fragment {
private ArrayAdapter<String> mFoursquareAdapter;
public FoursquareInfoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Dummy data for the ListView. Here's the sample weekly forecast
String[] data = {
"Sample Foursquare Data",
};
List<String> foursquareList = new ArrayList<String>(Arrays.asList(data));
mFoursquareAdapter = new ArrayAdapter<String>(
getActivity(), // the current context ie the activity
R.layout.fragment_my, // the name of the layout Id
R.id.textViewFoursquare, // the Id of the TextView to populate
foursquareList);
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
//View resultsView = inflater.inflate(R.layout.results, container, false);
View resultsView = inflater.inflate(R.layout.fragment_my, container, false);
ListView listView = (ListView) resultsView.findViewById(R.id.listview_FoursquareInfo);
listView.setAdapter(mFoursquareAdapter);
Button btnGetFoursquareData = (Button) rootView.findViewById(R.id.btnFoursquare);
btnGetFoursquareData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FetchFoursquareDataTask fetch = new FetchFoursquareDataTask();
fetch.execute("Starbucks");
}
});
return rootView;
}
public class FetchFoursquareDataTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchFoursquareDataTask.class.getSimpleName();
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
mFoursquareAdapter.clear();
for (String ItemStr : result) {
mFoursquareAdapter.add(ItemStr);
}
mFoursquareAdapter.notifyDataSetChanged();
}
}
#Override
protected String[] doInBackground(String... params) {
// If there's no venue category, theres nothing to look up. Verify the size of the params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String foursquareJsonStr = null;
try {
// Build Foursquare URI with Parameters
final String FOURSQUARE_BASE_URL =
"https://api.foursquare.com/v2/venues/search";
final String client_id = "client_id";
final String client_secret = "client_secret";
final String v = "20130815";
final String near = "Dunwoody, Ga";
final String query = "Starbucks";
final String limit = "2";
Uri builtUri = Uri.parse(FOURSQUARE_BASE_URL).buildUpon()
.appendQueryParameter("client_id", client_id)
.appendQueryParameter("client_secret", client_secret)
.appendQueryParameter("v", v)
.appendQueryParameter("near", near)
.appendQueryParameter("query", query)
.appendQueryParameter("limit", limit)
.build();
URL url = new URL(builtUri.toString());
// Create the request to Foursquare, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
foursquareJsonStr = null;
return null;
}
foursquareJsonStr = buffer.toString();
Log.v(LOG_TAG, "Foursquare JSON String: " + foursquareJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the fpursquare data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
String[] list = new String[]{"", ""};
try {
JSONObject foursquareJson = new JSONObject(foursquareJsonStr);
JSONObject responseObject = (JSONObject) foursquareJson.get("response");
JSONArray foursquareArray = responseObject.getJSONArray("venues");
list = new String[foursquareArray.length()];
for (int i = 0; i < foursquareArray.length(); i++) {
list[i] = foursquareArray.get(i).toString();
}
return list;
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
Log.e(LOG_TAG, "ba");
return list;
}
}
}
}
This
mFoursquareAdapter.add(ItemStr);
Should be
foursquareList.add(ItemStr)
And you'll need to declare foursquareList properly (as a field).
You should also declare your Adapter as a field variable as well, just in case you need to reference it later