I would like to stop listview after loading from server instead of moving up when I scrolldown veryfast.
I tired setFriction property also but it doesn't seem to be that much effective.
Can anybody suggest how to control this?
This is my code.
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
View footerView;
ProgressDialog progress;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
dataArrayList = new ArrayList<DataObject>();
footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
if (isOnline(_activity)) {
progress = new ProgressDialog(this);
lv.setFriction(ViewConfiguration.getScrollFriction() * 0.5f);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
// ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (dataArrayList.size() == 0) {
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
loadingMore = true;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progress.dismiss();
try {
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
// dataListAdapter.add(dataObject);
}
lv.addFooterView(footerView);
dataListAdapter.notifyDataSetChanged();
loadingMore = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}
Related
I just created my recyclerview to show a cardview when I just filling the required data on AddNewTimerFragment.java. But somehow it wont show the card that contains the data that I've fill in before. I've tried to changes something, but doesn't work.
Code :
MainActivity.java
package com.mobprog.ius.dwasu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private ArrayList<MyListDataTimer> mintervalTimeList = new ArrayList();
private RecyclerView mRecyclerView;
private alarmListAdapter mAdapter;
public boolean isFragmentAddNewAlarmDisplayed = false;
static final String STATE_FRAGMENT = "state_of_fragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.textUserName)).setText("Hello " + getSharedPreferences("Dwasu", 0).getString("user", ""));
if (getSharedPreferences("Dwasu", 0) == null || !getSharedPreferences("Dwasu", 0).contains("user")) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(getApplicationContext(), mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
if (savedInstanceState != null)
isFragmentAddNewAlarmDisplayed = savedInstanceState.getBoolean(STATE_FRAGMENT);
Button mnewReminderButton = findViewById(R.id.newReminder);
mnewReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.class.getSimpleName(),"Button Clicked");
displayFragment();
}
});
ImageButton mlogOutButton = findViewById(R.id.logOutButton);
findViewById(R.id.logOutButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSharedPreferences("Dwasu", 0).edit().clear().apply();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
// // Get the Drawable custom_progressbar
// Drawable draw = ResourcesCompat.getDrawable(getResources(), R.drawable.progress_bar, null);
// // set the drawable as progress drawable
// ProgressBar.setProgressDrawable(draw);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state of the fragment (true=open, false=closed).
savedInstanceState.putBoolean(STATE_FRAGMENT, isFragmentAddNewAlarmDisplayed);
super.onSaveInstanceState(savedInstanceState);
}
public void closeFragment(){
// Get the FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
// Check to see if the fragment is already showing.
AddNewTimerFragment simpleFragment = (AddNewTimerFragment) fragmentManager
.findFragmentById(R.id.FragmentContainer_AddNewAlarm);
if (simpleFragment != null) {
// Create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.remove(simpleFragment).commit();
}
// Set boolean flag to indicate fragment is closed.
isFragmentAddNewAlarmDisplayed = false;
}
public void displayFragment(){
AddNewTimerFragment simpleFragment = AddNewTimerFragment.newInstance();
// Get the FragmentManager and start a transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the SimpleFragment.
fragmentTransaction.add(R.id.FragmentContainer_AddNewAlarm,
simpleFragment).addToBackStack(null).commit();
// Set boolean flag to indicate fragment is open.
isFragmentAddNewAlarmDisplayed = true;
}
}
AddNewTimerFragment.java
package com.mobprog.ius.dwasu;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import static android.content.Context.MODE_PRIVATE;
public class AddNewTimerFragment extends Fragment {
Button startTime;
Button endTime;
Button meditConfirm_button;
int startHour;
int startMinute;
int endHour;
int endMinute;
int position = 1;
long totalSize = 0;
String value;
ProgressDialog progDailog;
View rootview;
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
public AddNewTimerFragment() {
// Required empty public constructor
}
public static AddNewTimerFragment newInstance() {
return new AddNewTimerFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_new_alarm,
container, false);
rootview = rootView;
/*Shared Pref*/
mPreferences = this.getActivity().getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
SharedPreferences.Editor mPreferencesEditor = mPreferences.edit();
ImageButton mbtnCloseFragment = rootView.findViewById(R.id.btnCloseFragment);
mbtnCloseFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).closeFragment();
}
});
// initiate the edit text
startTime = rootView.findViewById(R.id.startTimePick);
startTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
startTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
startHour = mcurrentTime.get(Calendar.HOUR);
startMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mStartTimePicker;
mStartTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedStartHour, int selectedStartMinute) {
if (selectedStartMinute == 0) {
startTime.setText(selectedStartHour + ":00");
} else if (selectedStartMinute < 10) {
if (selectedStartHour < 10) {
startTime.setText("0" + selectedStartHour + ":0" + selectedStartMinute);
}
} else {
startTime.setText(selectedStartHour + ":" + selectedStartMinute);
}
startHour = selectedStartHour;
}
}, startHour, startMinute, true);//Yes 24 hour time
mStartTimePicker.show();
}
});
endTime = rootView.findViewById(R.id.endTimePick);
endTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
endTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
endHour = mcurrentTime.get(Calendar.HOUR);
endMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mEndTimePicker;
mEndTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedEndHour, int selectedEndMinute) {
if (selectedEndMinute == 0) {
endTime.setText(selectedEndHour + ":00");
} else if (selectedEndMinute < 10) {
if (selectedEndHour < 10) {
endTime.setText("0" + selectedEndHour + ":0" + selectedEndMinute);
}
} else {
endTime.setText(selectedEndHour + ":" + selectedEndMinute);
}
endHour = selectedEndHour;
}
}, endHour, endMinute, true);//Yes 24 hour time
mEndTimePicker.show();
}
});
Spinner spinner = (Spinner) rootView.findViewById(R.id.timeIntervalPick);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.listtimer, R.layout.spinner_support);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String[] valueListTimer = getResources().getStringArray(R.array.valueListTimer);
value = valueListTimer[position];
Log.e("Value of Spinner", value);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(value);
new MyListDataTimer(String.valueOf(startHour),String.valueOf(endHour),String.valueOf(value),String.valueOf(position));
new UploadAlarmDataToServer().execute();
position++;
}
});
// Inflate the layout for this fragment
return rootView;
}
private class UploadAlarmDataToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progDailog = new ProgressDialog(getContext());
progDailog.setMessage("Menyimpan...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.setCanceledOnTouchOutside(false);
progDailog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String data = null;
try {
data = sendDataTimer();
} catch (Exception e) {
e.printStackTrace();
data = "Gagal";
}
return data;
}
public String sendDataTimer() throws Exception {
URL url = new URL("https://ius.mobile.indoserver.web.id/alarmData.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("startHour", new StringBody(startHour + ""));
entity.addPart("endHour", new StringBody(endHour + ""));
entity.addPart("intervalWaktu", new StringBody(value + ""));
totalSize = entity.getContentLength();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.addRequestProperty("Content-length", totalSize + "");
con.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = con.getOutputStream();
entity.writeTo(con.getOutputStream());
os.close();
con.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
if (result != null) {
Log.e("UPLOAD", result);
if (result.equalsIgnoreCase("OK")) {
Toast.makeText(getContext(), "Data Alarm tersimpan", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}
}
super.onPostExecute(result);
}
}
}
alarmListAdapter.java
package com.mobprog.ius.dwasu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
public class alarmListAdapter extends RecyclerView.Adapter<alarmListAdapter.alarmListHolder>{
private final ArrayList<MyListDataTimer> mintervalTimeList;
private LayoutInflater mInflater;
public alarmListAdapter(Context context, ArrayList<MyListDataTimer> mintervalTimeList) {
mInflater = LayoutInflater.from(context);
this.mintervalTimeList = mintervalTimeList;
}
#Override
public alarmListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.alarm_item,
parent, false);
return new alarmListHolder(mItemView, this);
}
#Override
public void onBindViewHolder(alarmListAdapter.alarmListHolder holder, int position) {
final MyListDataTimer myListData = mintervalTimeList.get(position);
holder.mintervalTime.setText(myListData.getIntervalWaktu());
holder.mtimeWork.setText(myListData.getStartHour() +":00 - " + myListData.getEndHour() +":00");
}
#Override
public int getItemCount() {
return mintervalTimeList.size();
}
public class alarmListHolder extends RecyclerView.ViewHolder {
public TextView mintervalTime;
public TextView mtimeWork;
final alarmListAdapter mAdapter;
public alarmListHolder(View itemView, alarmListAdapter adapter) {
super(itemView);
mintervalTime = itemView.findViewById(R.id.intervalTime);
mtimeWork = itemView.findViewById(R.id.timeWork);
this.mAdapter = adapter;
}
}
}
**MyListDataTimer.java**
package com.mobprog.ius.dwasu;
public class MyListDataTimer {
private String startHour;
private String endHour;
private String intervalWaktu;
private String position;
public MyListDataTimer(String startHour, String endHour, String intervalWaktu, String position) {
this.startHour = startHour;
this.endHour = endHour;
this.intervalWaktu = intervalWaktu;
this.position = position;
}
public String getStartHour() {
return startHour;
}
public void setStartHour(String startHour) {
this.startHour = startHour;
}
public String getEndHour() {
return endHour;
}
public void setEndHour(String endHour) {
this.endHour = endHour;
}
public String getIntervalWaktu() {
return intervalWaktu;
}
public void setIntervalWaktu(String intervalWaktu) {
this.intervalWaktu = intervalWaktu;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
How to get Variable in doInBackground Get out of AsyncTask
Request Api url set new like and get new like and like mode
Now how to get new like and like mode out of AsyncTask for use setText
get like this from GetDataLike AsyncTask:
new GetDataLike().execute(textViewQuoteId.getText().toString());
String newLike = GetDataLike().newLike; // get like this from GetDataLike
String modeLike = GetDataLike().modeLike; // get like this from GetDataLike
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
Toast.LENGTH_LONG).show();
Json result example:
{"Like":{"quote_like":"27","quote_like_mode":"1"}}
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import static android.content.Context.CLIPBOARD_SERVICE;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی");
vh.textViewQuoteShare.setText("اشتراک");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
public final TextView textViewQuoteLikeIcon;
public final TextView textViewQuoteShareIcon;
public final TextView textViewQuoteCopyIcon;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId, TextView textViewQuoteLikeIcon, TextView textViewQuoteShareIcon, TextView textViewQuoteCopyIcon) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
this.textViewQuoteLikeIcon = textViewQuoteLikeIcon;
this.textViewQuoteShareIcon = textViewQuoteShareIcon;
this.textViewQuoteCopyIcon = textViewQuoteCopyIcon;
}
public static ViewHolder create(final RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
final TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
final TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
final TextView textViewQuoteLikeIcon = (TextView) rootView.findViewById(R.id.textViewQuoteLikeIcon);
final TextView textViewQuoteShareIcon = (TextView) rootView.findViewById(R.id.textViewQuoteShareIcon);
final TextView textViewQuoteCopyIcon = (TextView) rootView.findViewById(R.id.textViewQuoteCopyIcon);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");
currentLike = currentLike.replace(")","");
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
Toast.LENGTH_LONG).show();
}
});
textViewQuoteLikeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");
currentLike = currentLike.replace(")","");
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
Toast.LENGTH_LONG).show();
}
});
Typeface font = Typeface.createFromAsset( rootView.getContext().getAssets(), "fontawesome-webfont.ttf" );
textViewQuoteLikeIcon.setTypeface(font);
textViewQuoteLikeIcon.setText(String.valueOf((char) 0xf164));
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId, textViewQuoteLikeIcon, textViewQuoteShareIcon, textViewQuoteCopyIcon);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_like_mode = innerObject.getString(Keys.KEY_QUOTE_LIKE_Mode);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
you just have to return string from doInBackground method and in onPostExecute method you can setText.for more than one values which is in your case you should do like this
public class CollectValues{
public String quote_like;
public String quote_like_mode;}
and now in doInBackground method you should do like this
CollectValue cv = new CollectValue();
cv.quote_like=//your response;
cv.quote_like=//your response;
return cv;
and finally in onPostExecute method you should do like this
#Override
protected void onPostExecute(CollectValues cv) {
//your textview here
textview1.setText(cv.quote_like);
textview2.setText(cv.quote_like_mode);
}
this will solve your problem..
i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.
How to swipe my full screen images from gridview...and that images should Loading from JSON response...?
i'm new to android...please help me friends...
But i want to use only One url in my program(JSON URL)...from that i need
Gridview--->FullScreenImage(zooming and swiping)
This is my gridView Activity...
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.GridView;
import android.widget.ListView;
import com.example.admin.adapter.GridViewImageAdapter;
import com.example.admin.helper.AppConstant;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
// ArrayList<HashMap<String, String>> imagePaths;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
new DownloadJSON().execute();
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() -
((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(GridViewActivity.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
imagePaths = new ArrayList<>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
imagePaths.add( jsonobject.getString("name"));
imagePaths.add(jsonobject.getString("country"));
imagePaths.add( jsonobject.getString("spouse"));
imagePaths.add(jsonobject.getString("image"));
// Set the JSON Objects into the array
// imagePaths.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
gridView = (GridView) findViewById(R.id.grid_view);
// Pass the results into ListViewAdapter.java
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth);
// Set the adapter to the ListView
gridView.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
this is my Gridview Adapter...
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.admin.loadingimagefromwebgridandswipe.FullScreenViewActivity;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this.activity = activity;
this.filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.filePaths.size();
}
#Override
public Object getItem(int position) {
return this.filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
} else {
imageView = (ImageView) convertView;
}
String designationUrl = filePaths.get(position);
// Log.d("designationUrl",""+designationUrl);
// URL url = null;
// try {
// url = new URL(designationUrl);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
Picasso.with(activity)
.load(designationUrl)
.resize(imageWidth, imageWidth).into(imageView);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
//Toast.makeText(GridViewImageAdapter.this,"url: "+designationUrl,Toast.LENGTH_LONG).show();
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Toast.makeText(GridViewImageAdapter.this,"url: "+,Toast.LENGTH_LONG).show();
Intent i = new Intent(activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Fullscreen imageViewActivity....
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import com.example.admin.Application;
import com.example.admin.adapter.FullScreenImageAdapter;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
private ImageView flag;
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
//flag=(ImageView)findViewById(R.id.flag);
image=(ImageView)findViewById(R.id.image);
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
Application.url());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
FullScreenImageAdapter:
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.example.admin.helper.TouchImageView;
import com.example.admin.ndimageslider.R;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.util.ArrayList;
public class FullScreenImageAdapter extends PagerAdapter {
private Activity activity;
private ArrayList<String> imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this.activity = activity;
this.imagePaths = imagePaths;
}
#Override
public int getCount() {
return this.imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
// imgDisplay.setImageBitmap(bitmap);
Picasso.with(activity)
.load(imagePaths.get(position)).into(imgDisplay);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.finish();
}
});
((ViewPager) container).addView(viewLayout,0);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Application:
package com.example.admin;
import android.widget.Toast;
import com.example.admin.helper.FileCache;
import java.util.ArrayList;
public class Application extends android.app.Application {
public static ArrayList<String> url(){
ArrayList<String> filePaths = new ArrayList<String>();
filePaths.add("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
return filePaths;
}
}
JSONfunctions:
package com.example.admin.helper;
/**
* Created by Admin on 14-03-2016.
*/
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
you'll have to implement Viewpage in your application. Take a look at this tutorial for the application you are trying to make.
http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/
Follow this link. Cheers.
Hi I try to share a text with button in ListAdapter.java :
But it doesn't work How can I set View in Onclick void for button ?
I use fragment for lists
see my code :
package com.kamalan.phpandroidapi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class VoteListAdapter extends BaseAdapter {
// protected static final Context VoteListAdapter.this = null;
private final String TAG = "*** VoteListAdapter ***";
private LayoutInflater myInflater;
private List<Vote> vote;
public VoteListAdapter(Context context) {
myInflater = LayoutInflater.from(context);
}
public void setData(List<Vote> vote) {
this.vote = vote;
}
#Override
public int getCount() {
return vote.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvDate);
holder.ratingBar = (RatingBar) convertView.findViewById(R.id.ratingBar);
holder.sharebtn = (Button) convertView.findViewById(R.id.sharebtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(vote.get(position).getName());
holder.tvComment.setText(vote.get(position).getComment());
holder.tvDate.setText(getFormatedDate(vote.get(position).getPublishDate()));
holder.ratingBar.setRating(Integer.parseInt(vote.get(position).getRate()));
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
String text = (String) holder.tvComment.getText();
//Toast.makeText(context, ab, Toast.LENGTH_LONG).show();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,text);
try {
context.startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}
};
holder.sharebtn.setOnClickListener(clickListener);
return convertView;
}
private String getFormatedDate(String date) {
String myDate = null;
try {
Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
} catch (ParseException e) {
myDate = "";
e.printStackTrace();
}
return myDate;
}
static class ViewHolder {
public Button sharebtn;
TextView tvName;
TextView tvComment;
TextView tvDate;
RatingBar ratingBar;
}
}
and FragmentComment.java :
package com.kamalan.phpandroidapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.kamalan.phpandroidapi.FragmentForm.OnSendingRequestToServer;
//import com.kamalan.phpandroidapi.FragmentForm.SendFormTask;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentComment extends Fragment {
private final String TAG = "FragmentComment";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private Spinner spinner;
private ListView listView;
private List<Vote> voteList;
private VoteListAdapter listAdapter;
int ab = 1;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_comments, container, false);
spinner = (Spinner) view.findViewById(R.id.spinner);
final TextView refresh = (TextView) view.findViewById(R.id.closetag);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// ActionBar actionBar = context.getSupportActionBar();
//getSupportActionBar();
// actionBar.hide();
//android.app.ActionBar bar = getActivity().getActionBar();
//bar.hide();
if (ab == 1){
ab = 0;
refresh.setText("کوچک کردن");
spinner.setVisibility(View.GONE);
android.app.ActionBar bar = getActivity().getActionBar();
bar.hide();
}else{
ab = 1;
refresh.setText("تمام صفحه");
spinner.setVisibility(View.VISIBLE);
android.app.ActionBar bar = getActivity().getActionBar();
bar.show();
}
}
});
// TextView tvComment = (TextView) view.findViewById(R.id.tvComment);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String deviceId = "all";
voteList.clear();
if(pos == 1){
//deviceId = getDeviceId();
deviceId = "c1";
}else if(pos == 2){
deviceId = "c2";
}else if(pos == 3){
deviceId = "c3";
}else if(pos == 4){
deviceId = "c4";
}else if(pos == 5){
deviceId = "c5";
}else if(pos == 6){
deviceId = "c6";
}else if(pos == 7){
deviceId = "c7";
}else if(pos == 8){
deviceId = getDeviceId();
}
voteList.clear();
new RequestVoteTask(deviceId).execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
listView = (ListView) view.findViewById(R.id.listView);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
voteList = new ArrayList<Vote>();
listAdapter = new VoteListAdapter(context);
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class RequestVoteTask extends AsyncTask<Void, Void, Boolean> {
String deviceId;
RequestVoteTask(String deviceId) {
this.deviceId = deviceId;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "RequestVoteTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getCommentAPI(deviceId));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
JSONObject jObject = new JSONObject(response);
JSONArray jsonArray = jObject.getJSONArray("posts");
for(int i=0; i<jsonArray.length(); i++){
Vote vote = new Vote();
vote.setDeviceId(jsonArray.getJSONObject(i).getString("DeviceId"));
vote.setName(jsonArray.getJSONObject(i).getString("FullName"));
vote.setRate(jsonArray.getJSONObject(i).getString("Rate"));
vote.setComment(jsonArray.getJSONObject(i).getString("Comment"));
vote.setPublishDate(jsonArray.getJSONObject(i).getString("PublishTime"));
voteList.add(vote);
}
if(voteList.size() >= 1)
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "RequestVoteTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(!result)
Toast.makeText(context, "جکی موجود نیست", Toast.LENGTH_LONG).show();
// for(int i=0; i<voteList.size(); i++)
// Log.d("Item " + i, voteList.get(i).toString());
listAdapter.setData(voteList);
listView.setAdapter(listAdapter);
}
}
}
I try to write getView or inflate and ... but it doesn't work
Try this way,hope this will help you to solve your problem.
public class VoteListAdapter extends BaseAdapter {
private final String TAG = "*** VoteListAdapter ***";
private Context context;
private ArrayList<Vote> votes;
public VoteListAdapter(Context context,ArrayList<Vote> votes) {
this.context =context;
this.votes =votes;
}
#Override
public int getCount() {
return votes.size();
}
#Override
public Object getItem(int position) {
return votes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvDate);
holder.ratingBar = (RatingBar)convertView.findViewById(R.id.ratingBar);
holder.sharebtn = (Button) convertView.findViewById(R.id.sharebtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(votes.get(position).getName());
holder.tvComment.setText(votes.get(position).getComment());
holder.tvDate.setText(getFormatedDate(votes.get(position).getPublishDate()));
holder.ratingBar.setRating(Integer.parseInt(votes.get(position).getRate()));
holder.sharebtn.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,votes.get(position).getComment());
try {
context.startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}
});
return convertView;
}
private String getFormatedDate(String date) {
String myDate = null;
try {
Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
} catch (ParseException e) {
myDate = "";
e.printStackTrace();
}
return myDate;
}
static class ViewHolder {
Button sharebtn;
TextView tvName;
TextView tvComment;
TextView tvDate;
RatingBar ratingBar;
}
}
public class FragmentComment extends Fragment {
private final String TAG = "FragmentComment";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private Spinner spinner;
private ListView listView;
private List<Vote> voteList;
private VoteListAdapter listAdapter;
int ab = 1;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_comments, container, false);
spinner = (Spinner) view.findViewById(R.id.spinner);
final TextView refresh = (TextView) view.findViewById(R.id.closetag);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// ActionBar actionBar = context.getSupportActionBar();
//getSupportActionBar();
// actionBar.hide();
//android.app.ActionBar bar = getActivity().getActionBar();
//bar.hide();
if (ab == 1){
ab = 0;
refresh.setText("کوچک کردن");
spinner.setVisibility(View.GONE);
android.app.ActionBar bar = getActivity().getActionBar();
bar.hide();
}else{
ab = 1;
refresh.setText("تمام صفحه");
spinner.setVisibility(View.VISIBLE);
android.app.ActionBar bar = getActivity().getActionBar();
bar.show();
}
}
});
// TextView tvComment = (TextView) view.findViewById(R.id.tvComment);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String deviceId = "all";
voteList.clear();
if(pos == 1){
//deviceId = getDeviceId();
deviceId = "c1";
}else if(pos == 2){
deviceId = "c2";
}else if(pos == 3){
deviceId = "c3";
}else if(pos == 4){
deviceId = "c4";
}else if(pos == 5){
deviceId = "c5";
}else if(pos == 6){
deviceId = "c6";
}else if(pos == 7){
deviceId = "c7";
}else if(pos == 8){
deviceId = getDeviceId();
}
voteList.clear();
new RequestVoteTask(deviceId).execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
listView = (ListView) view.findViewById(R.id.listView);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
voteList = new ArrayList<Vote>();
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class RequestVoteTask extends AsyncTask<Void, Void, Boolean> {
String deviceId;
RequestVoteTask(String deviceId) {
this.deviceId = deviceId;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "RequestVoteTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getCommentAPI(deviceId));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
JSONObject jObject = new JSONObject(response);
JSONArray jsonArray = jObject.getJSONArray("posts");
for(int i=0; i<jsonArray.length(); i++){
Vote vote = new Vote();
vote.setDeviceId(jsonArray.getJSONObject(i).getString("DeviceId"));
vote.setName(jsonArray.getJSONObject(i).getString("FullName"));
vote.setRate(jsonArray.getJSONObject(i).getString("Rate"));
vote.setComment(jsonArray.getJSONObject(i).getString("Comment"));
vote.setPublishDate(jsonArray.getJSONObject(i).getString("PublishTime"));
voteList.add(vote);
}
if(voteList.size() >= 1)
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "RequestVoteTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(!result)
Toast.makeText(context, "جکی موجود نیست", Toast.LENGTH_LONG).show();
// for(int i=0; i<voteList.size(); i++)
// Log.d("Item " + i, voteList.get(i).toString());
listAdapter = new VoteListAdapter(context,voteList);
listView.setAdapter(listAdapter);
}
}
}