Trying to make an API call to the url below and parse the returning JSON, when the "refresh" button is called.
I can link to a button and get text (Hello world) to the screen, but can't seem to link the button click to the API request. Error message says I cannot reference non-static method "execute" from a static context
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void retrieveInformation(View view){
RetrieveFeedTask.execute();
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
String jsonString = "";
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL("www.liftin.co.uk/api/v1/journeys");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
jsonString = response;
try {
getInformationFromJson(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getInformationFromJson(String jsonString)
throws JSONException {
final String DRIVER = "driver";
final String START = "start";
final String DESTINATION = "destination";
final String TIME = "pick_up_time";
final String PASSENGERS = "passengers";
final String SEATS = "seats_available";
JSONObject journeyJson = new JSONObject(jsonString);
String time = journeyJson.getString(TIME);
String seats = journeyJson.getString(SEATS);
String results = seats + "-----" + time;
return results;
}
}
}
Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.liftin.MainActivity">
<Button
android:id="#+id/queryButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Refresh"
android:onClick="retrieveInformation"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/responseView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
</LinearLayout>
You should create asynchronous call for your AsyncTask like this :
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(); //asynchronous call
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
UPDATE
If you want to set data to textview after parsing data. You have to make little bit changes in your activity as follows.
You should initialize your textview in onCreate() and make it global variable for your activity, so that you can access it in full activity.
then in your onPostExecute() do this :
textview.setText(getInformationFromJson(response));
Hope it will Help :)
You must create a object of AsyncTask (RetrieveFeedTask) before calling it. For example
public void retrieveInformation(View view){
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
new RetrieveFeedTask().execute();
}
You still need to pass something for Void.
public void retrieveInformation(View view){
new RetrieveFeedTask().execute(null);
TextView textview = (TextView) findViewById(R.id.responseView);
textview.setText("Hello world");
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Im Getting invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at app.VOTD_Data.onPostExecute.
Async Task
public class VOTD_Data extends AsyncTask<Void, Void, Void> {
private String verseData = "";
private String dailyverse = "";
private String verseauthor = "";
private String dailVersePref = "";
private String verseAuthorPref = "";
private SharedPreferences sharedPreferences;
private Context context;
public VOTD_Data(Context context){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
dailVersePref = sharedPreferences.getString("dailyverse", "");
verseAuthorPref = sharedPreferences.getString("verseauthor", "");
}
public VOTD_Data() {
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://beta.ourmanna.com/api/v1/get/?format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
verseData = verseData + line;
}
JSONObject mainObject = new JSONObject(verseData).getJSONObject("verse");
JSONObject verseObject = mainObject.getJSONObject("details");
dailyverse = verseObject.getString("text");
verseauthor = verseObject.getString("reference");
sharedPreferences
.edit()
.putString("dailyverse", dailyverse)
.putString("verseauthor", verseauthor)
.apply();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Daily Verse Activity
DailyVerse_Activity.data.setText(dailyverse.toString());
}
}
Main Activity
public class DailyVerse_Activity extends AppCompatActivity {
public static TextView data;
private ImageView banner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_verse);
data = (TextView) findViewById(R.id.dataText);
VOTD_Data process = new VOTD_Data(DailyVerse_Activity.this);
process.execute();
}
//On Back Pressed
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
finish();
return true;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DailyVerse_Activity">
<TextView
android:id="#+id/dataText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:gravity="center"
android:hint="Verse Data"
/>
</RelativeLayout>
Im Getting invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at app.VOTD_Data.onPostExecute.app.VOTD_Data.onPostExecute(VOTD_Data.java:88)
at app.VOTD_Data.onPostExecute(VOTD_Data.java:18)
Pass your rootView to AsyncTask and get it's reference from there. Add one more parameter in your VOTD_Data class like this.
public VOTD_Data(Context context, TextView textView)
In postExecute just do:
textView.setText(dailyverse.toString());
And in your Activity class while calling the AsyncTask pass the textView to VOTD_Data class constructor like this:
VOTD_Data process = new VOTD_Data(DailyVerse_Activity.this, data);
process.execute();
I am new to Android development, trying to create my own app. It should display a particular YouTube Channel by using the YouTube Data API. I have started with the standard bottom navigation template in Android Studio and used the following project on Github for some start-up help. https://github.com/stressGC/Remake-YouTube-Android
I had to change a few things like the deprecated http call inside the code to keep it running with the new Android APKs. Everything seems fine from my point of view: I can see that the API content looks good and that each title / description / publishdate is placed in the according variables. There is also no error message in the log. When I start the emulator, the app is running fine. But as soon as I switch to the "Dashboard" fragment (where the code is placed), it is empty.
DashboardFragment.java
public class DashboardFragment extends Fragment {
private static String API_KEY = "hidden"; //normaler API key ohne limits, kein oauth
private static String CHANNEL_ID = "hidden";
private static String CHANNEL_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId="+CHANNEL_ID+"&maxResults=20&key="+API_KEY+"";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YouTubeDataModel> mListData = new ArrayList<>();
public DashboardFragment () {
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYouTubeAPI().execute();
return view;
}
private void initList(ArrayList<YouTubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData);
mList_videos.setAdapter(adapter);
}
// create asynctask to get data from youtube
private class RequestYouTubeAPI extends AsyncTask<Void, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
URL url = null;
String json = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(CHANNEL_GET_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
//HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
HttpURLConnection urlConnection = NetCipher.getHttpsURLConnection(url);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
json = sb.toString();
return json;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response != null){
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YouTubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YouTubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YouTubeDataModel youtubeObject = new YouTubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}
VideoPostAdapter.java
public class VideoPostAdapter extends RecyclerView.Adapter<VideoPostAdapter.YouTubePostHolder> {
private ArrayList<YouTubeDataModel> dataSet;
private Context mContext = null;
public VideoPostAdapter(Context mContext, ArrayList<YouTubeDataModel> dataSet) {
this.dataSet = dataSet;
this.mContext = mContext;
}
#NonNull
#Override
public YouTubePostHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_post_layout,parent,false);
YouTubePostHolder postHolder = new YouTubePostHolder(view);
return postHolder;
}
#Override
public void onBindViewHolder(#NonNull YouTubePostHolder holder, int position) {
// set the views here
TextView textViewTitle = holder.textViewTitle;
TextView textViewDes = holder.textViewDes;
TextView textViewDate = holder.textViewDate;
ImageView ImageThumb = holder.ImageThumb;
YouTubeDataModel object = dataSet.get(position);
textViewTitle.setText(object.getTitle());
textViewDes.setText(object.getDescription());
textViewDate.setText(object.getPublishedAt());
// image will be downloaded from url
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class YouTubePostHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDes;
TextView textViewDate;
ImageView ImageThumb;
public YouTubePostHolder(#NonNull View itemView) {
super(itemView);
this.textViewTitle = (TextView) itemView.findViewById(R.id.textViewTitle);
this.textViewDes = (TextView) itemView.findViewById(R.id.textViewDes);
this.textViewDate = (TextView) itemView.findViewById(R.id.textViewDate);
this.ImageThumb = (ImageView) itemView.findViewById(R.id.ImageThumb);
}
}
}
YouTubeDataModel.java
public class YouTubeDataModel {
private String title = "";
private String description = "";
private String publishedAt = "";
private String thumbnail = "";
public String getVideo_id() {
return video_id;
}
public void setVideo_id(String video_id) {
this.video_id = video_id;
}
private String video_id = "";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
youtube_post_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ImageView
android:id="#+id/ImageThumb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"/>
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="published at"
android:singleLine="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:textColor="#android:color/white"
android:textSize="12dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video Title"
android:singleLine="true"
android:textColor="#android:color/white"
android:textSize="22dp"/>
<TextView
android:id="#+id/textViewDes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video description"
android:singleLine="true"
android:textColor="#android:color/white"
android:textSize="12dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/mList_videos"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Unfortunately I have no idea why the fragment is still empty. And without any error in Android Studio log I really hope you can help me :/
Inside your RequestYouTubeAPI ASyncTask you have this error code:
} catch (IOException e) {
e.printStackTrace();
return null;
}
Then in onPostExecute you have the following:
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response != null){
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Therefore if you get an error, you return null and if onPostExecute is given a null response it does nothing.
So this one place you could have an error and therefore a blank fragment.
Before you fix this, you can prove this is happening like so:
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(response == null){
Log.e("TUT", "We did not get a response, not updating the UI.");
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You can fix this two ways:
in doInBackground change the catch to this:
} catch (IOException e) {
Log.e("TUT", "error", e);
// Change this JSON to match what the parse expects, so you can show an error on the UI
return "{\"yourJson\":\"error!\"}";
}
or onPostExecute:
if(response == null){
List errorList = new ArrayList();
// Change this data model to show an error case to the UI
errorList.add(new YouTubeDataModel("Error");
mListData = errorList;
initList(mListData);
} else {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
//adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope that helps, there may be other errors in the code but this is one case that can happen if there is a problem with the API, the Json, the authorization, the internet etc.
I have a login page on fragment connected to BackgroundWorker class which has database connectivity.
my login page sends texts from EditTexts to BackgroundWorker Class, then all the database queries(by accessing PHP files from WAMP) are done in the BackgroundWorker class.
When i click the login button on my fragment it opens the dialog box which tells me if login was successful or not. (the code of dialog box exists in BackgroundWorker class (Please refer the code if i am not being clear) )
but the thing is, i don't want dialog box, i want to go from one fragment to another from that BackgroundWorker.java file.
i have the code of how can i go from one activity to another, but not of fragment
fragment XML FILE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.admin.blingiton.Client_login">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:id="#+id/ClientLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="600dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:scaleType="fitXY"
app:srcCompat="#drawable/back" />
<ImageView
android:id="#+id/mirae"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="12dp"
android:layout_marginStart="32dp"
android:scaleType="centerInside"
app:srcCompat="#drawable/mirae" />
<ImageView
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="600dp"
android:layout_alignBottom="#+id/mirae"
android:layout_alignParentStart="true"
android:layout_marginBottom="20dp"
android:scaleType="fitStart"
app:srcCompat="#drawable/header" />
<EditText
android:id="#+id/cusername"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignTop="#+id/mirae"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:background="#drawable/username"
android:ems="10"
android:hint="username"
android:inputType="textPersonName"
android:textAlignment="center" />
<EditText
android:id="#+id/cpassword"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignStart="#+id/cusername"
android:layout_below="#+id/cusername"
android:layout_marginTop="18dp"
android:background="#drawable/password"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
android:textAlignment="center" />
<Button
android:id="#+id/clogin"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_above="#+id/signupbtn"
android:layout_alignStart="#+id/cpassword"
android:layout_marginBottom="11dp"
android:background="#drawable/login" />
<Button
android:id="#+id/signupbtn"
android:layout_width="200dp"
android:layout_height="35dp"
android:layout_alignBottom="#+id/mirae"
android:layout_alignStart="#+id/clogin"
android:background="#drawable/signup"
/>
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/log" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/afterlogin"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</RelativeLayout>
Fragment.java file
EditText UsernameEt, PasswordEt;
Button login;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_clientlogin, container, false);
UsernameEt = (EditText) v.findViewById(R.id.cusername);
PasswordEt = (EditText) v.findViewById(R.id.cpassword);
login = (Button) v.findViewById(R.id.clogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new
BackgroundWorker(getActivity());
backgroundWorker.execute(type, username, password);
}
});
return v;
}
BackgroundWorker.java < /b>
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String...params) {
String type = params[0];
String login_url = "http://192.168.10.2/login.php";
if (type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_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("user_name", "UTF-
8 ")+" = "+URLEncoder.encode(user_name,"
UTF - 8 ")+" & " +
URLEncoder.encode("password", "UTF-
8 ")+" = "+URLEncoder.encode(password,"
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 = ""; String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
Client_login cl = new Client_login();
alertDialog.setMessage(result);
//alertDialog.show();
if (result.contentEquals("login success !!!!! Welcome user")) {
//Code Here.
} else {
Toast toast = Toast.makeText(context, "Email or password is wrong",
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onProgressUpdate(Void...values) {
super.onProgressUpdate(values);
}
try to use this if you find any error please let me know.
First create a interface
interface ChangeFragment
{
public void chfragment();
}
Then your second fragment
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// this is your success login fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}
}
After that your activity where you place the login fragment
public class Successfull extends Activity implements ChangeFragment
{
protected void onCreate(android.os.Bundle savedInstanceState) {
//your code
}
}
#Override
public void chfragment()
{
SecondFragment yoursecondfragment=new SecondFragment();
FragmentManager manager=getSupportedFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.layout.framelayout,yoursecondfragment);
transaction.commit();
}
}
then your backgroundworker thread
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.10.2/login.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_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("user_name","UTF-
8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-
8")+"="+URLEncoder.encode(password,"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="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
Client_login cl = new Client_login();
alertDialog.setMessage(result);
//alertDialog.show();
if(result.contentEquals("login success !!!!! Welcome user")) {
//Code Here.
ChangeFragment frag=new Successfull();
frag.chfragment();
}else
{
Toast toast= Toast.makeText(context, "Email or password is wrong",
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
I think this code will help you.
The problem: When I Type a ID and press the button, it will not load the ID's webpage...
"a url" is the website page i'm trying to create, (Hidden for number of reasons)
It should be working, it loads the first site, but when I try to call for the IDs, the WebView does not change... Can someone please help me? -Thanks, JG1
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv.setWebViewClient(new OurViewClient());
wv.getSettings().setJavaScriptEnabled(true);
try {
String url = "a url";
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
String lid = "0";
//Clicking button changes to the color
}
final EditText idbox = (EditText) findViewById(R.id.editText1);
final Button idbutton = (Button) findViewById(R.id.idbtn);
final WebView wv = (WebView) findViewById(R.id.webView1);
public void onClick(View v) {
idbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String lid = idbox.getText().toString();
if (lid == "1") {
wv.setWebViewClient(new OurViewClient());
try {
String urla = "a url";
wv.loadUrl(urla);
} catch (Exception e) {
e.printStackTrace();
}
}
if (lid == "2") {
wv.setWebViewClient(new OurViewClient());
try {
String urlb = "a url";
wv.loadUrl(urlb);
} catch (Exception e) {
e.printStackTrace();
}
}
if (lid == "3") {
wv.setWebViewClient(new OurViewClient());
try {
String urlc = "a url";
wv.loadUrl(urlc);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
I guess, You had been called the same URL value like ("a url"). If yes, try to load different URLs in the web view.
If not, do the following changes in your code,
Put break points to debug your code where you get EditText value.
String lid = idbox.getText().toString(); //check lid is null or not
Change the if condition like this,
if(lid.equalsIgnoreCase("1"))
{
//task for rendering web page
}
Check your custom view client class.
Never mind, You written onClick() method definition is wrongly!
I confused because,
Have you been adding the onclick(android:onClick="onClick") function for button in xml.
In spite of I did some bit changes in your code,
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2" >
<EditText
android:id="#+id/urlValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1.5" />
<Button
android:id="#+id/urlBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="0.5"
android:text="load"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
private EditText getUrlValue;
private Button loadUrl;
private WebView webView;
String loadId = "";
String URL_ONE = "a_url";
String URL_TWO = "b_url";
String URL_THREE = "c_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getUrlValue = (EditText)findViewById(R.id.urlValue);
loadUrl = (Button)findViewById(R.id.urlBtn);
webView = (WebView)findViewById(R.id.webView);
//initial view for webView
getUrlValue.setText("1"); //here web page will load first url= "a url"
webView.setWebViewClient(new OurViewClient());
//onClick Event for load url button
loadUrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadId = getUrlValue.getText().toString();
if(loadId.equalsIgnoreCase("1")){
try{
webView.loadUrl(URL_ONE);
}catch (Exception e){
e.printStackTrace();
}
}
else if(loadId.equalsIgnoreCase("2")){
try{
webView.loadUrl(URL_TWO);
}catch (Exception e){
e.printStackTrace();
}
}
else{
try{
webView.loadUrl(URL_THREE);
}catch (Exception e){
e.printStackTrace();
}
}
}
});
}
}
remember to add internet permission in the manifest xml file.
Sorry that I'm asking such a question, but I'm tryin to make this one run for hours, and I'm not finding the mistake...
public class Main extends ListActivity {
/** Called when the activity is first created. */
ProgressDialog dialog;
#Override
public synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new WebLoader().doInBackground("http://sample.sample.com/sample.xml");
}
public class WebLoader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try{
URL url = new URL(params[0]);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(2048);
int current = 0;
while((current = bis.read()) != -1)
{
baf.append((byte)current);
}
result = new String(baf.toByteArray());
}
catch(Exception e)
{
Log.e("gullinews", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getApplicationContext(), "",
"Loading. Please wait...", true);
}
}
}
Running with a debugger shows, that the xml data is downloaded, but there's just black screen. When I tried "setContenView(R.layout.main);" with main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#android:id/list" />
</LinearLayout>
//Edit:
okay, I solved one error, didn't solve the rest. Source updated.
My Main problem now is, that I ain't got an Idea why the ProgressDialog doesnt show up. rest should be black, that's right.
new WebLoader().doInBackground("http://sample.sample.com/sample.xml");
That's not how you use an asynctask. Did you read any documentaton at all?